簡體   English   中英

Hostlistener 上的滾動事件

[英]scroll event on Hostlistener

我已經定義了模板

@Component({
    selector: 'name',
    directives: [ ... ],
    templateUrl: 'name.html'
})

和班級

export class ProductGridComponent implements OnInit {
    @HostListener('scroll', ['$event'])
    onScroll(e) {
        alert(window.pageYOffset)
    }

    products = [];
}

但它沒有拍攝任何東西,但是當我用 click 和 onClick 替換 scroll 和 onScroll 時,它確實顯示了警報。

為什么它不適用於 scroll ,angular2 是否有任何其他實現?

謝謝

假設您想顯示主機滾動(而不是 Windows 滾動)並且您使用的是 angular +2.1

  @HostListener('scroll', ['$event']) private onScroll($event:Event):void {
    console.log($event.srcElement.scrollLeft, $event.srcElement.scrollTop);
  };

您可以像下面這樣創建自定義指令

import { Directive, HostListener } from '@angular/core';

@Directive({
  selector: '[scroller]'
})
export class ScrollerDirective {

  @HostListener('scroll') scrolling(){
    console.log('scrolling');
  }

  @HostListener('click') clicking(){
    console.log('clicking...');
  }

  constructor() { }

}

然后假設您有一個 html 模板,例如

<div class="full-width" scroller>
    <div class="double-width"></div>
</div>

使用以下 css

.full-width{
    width: 200px;
    height: 200px;
    overflow: auto;
}

.double-width{
    width:400px;
    height: 100%;
}

如果您移動水平滾動條,控制台將在運行應用程序時打印“滾動”。

這里的關鍵是 - scoller 指令應該在父 div 中而不是在子 div 中。

@HostListener('document:wheel', ['$event.target'])
public onWheel(targetElement) {
    console.log()
}

在模板中的相應元素處設置(scroll)="yourFunction($event)"

您也可以通過以下代碼來完成:

import { HostListener} from "@angular/core";

@HostListener("window:scroll", [])
onWindowScroll() {
 //we'll do some stuff here when the window is scrolled
}

在 angular 10 及更高版本中,在偵聽窗口事件時執行以下操作:

import { HostListener } from '@angular/core';

@HostListener('window:scroll', ['$event']) onScroll($event: Event): void {
    if($event) {
      console.log($event));
    }
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM