Angular 7滚动事件不会触发

Jul*_*ida 5 angular-material angular angular7

用于在MatDialog组件的Angular应用中实现间谍导航栏。我实现了一个指令来监视使用的滚动事件

@HostListener('window:scroll', ['$event'])
Run Code Online (Sandbox Code Playgroud)

我也尝试'scroll'过使用事件名称。但是该事件似乎并未触发。我尝试了几种方法,例如通过直接在对话框组件中使用HostListener,使用JavaScript window.onscroll()函数和rxjs fromEvent()函数,但均未成功。

尝试其他CSS事件(例如window:click)工作正常。我还在没有显示为对话框的“正常”组件中进行了尝试,但该事件也未在其中触发。

这种行为可能是什么原因?

Jas*_*son 7

Here is an alternative solution which works rather well.

In short:

ngOnInit() {
    // Add an event listener to window
    // Window can be defined in the pollyfiles.ts as: 
    // if (window) {
    //    (window as any).global = window;
    // }
    window.addEventListener('scroll', this.scroll, true); //third parameter
}

ngOnDestroy() {
    window.removeEventListener('scroll', this.scroll, true);
}

scroll = (event: any): void => {
  // Here scroll is a variable holding the anonymous function 
  // this allows scroll to be assigned to the event during onInit
  // and removed onDestroy
  // To see what changed:
  const number = event.srcElement.scrollTop;
  console.log(event);
  console.log('I am scrolling ' + number);
};
Run Code Online (Sandbox Code Playgroud)


Jul*_*ida 6

出现这种现象的原因是,角形材料阻止了滚动事件。

我这样解决了:

  ngAfterViewInit(): void {

    const content = document.querySelector('.mat-dialog-container');
    const scroll$ = fromEvent(content, 'scroll').pipe(map(() => content));

    scroll$.subscribe(element => {
      // do whatever
    });
  }
Run Code Online (Sandbox Code Playgroud)