Angular 角度7滚动事件不触发

Angular 角度7滚动事件不触发,angular,angular-material,angular7,Angular,Angular Material,Angular7,用于在MatDialog组件中的我的Angular应用程序中实现间谍导航栏。 我使用 @HostListener('window:scroll', ['$event']) 我还尝试将“滚动”作为事件名称。但这一事件似乎并未引发。我尝试了几种方法,例如。G通过在对话框组件中直接使用HostListener,通过使用JavaScriptwindow.onscroll()函数和rxjsfromEvent()函数,但没有成功 尝试其他css事件(例如,窗口:单击)可以正常工作。 我还在一个“普通”组件

用于在MatDialog组件中的我的Angular应用程序中实现间谍导航栏。 我使用

@HostListener('window:scroll', ['$event'])
我还尝试将
“滚动”
作为事件名称。但这一事件似乎并未引发。我尝试了几种方法,例如。G通过在对话框组件中直接使用HostListener,通过使用JavaScript
window.onscroll()
函数和rxjs
fromEvent()
函数,但没有成功

尝试其他css事件(例如,
窗口:单击
)可以正常工作。 我还在一个“普通”组件中尝试了它,该组件没有显示为对话框,但事件也没有在那里触发


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

这种行为的原因是角度材质阻止了滚动事件

我是这样解决的:

  ngAfterViewInit(): void {

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

    scroll$.subscribe(element => {
      // do whatever
    });
  }
这里有一个比较好的替代方案

简言之:

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);
};

试试这个…不需要对html做任何事情

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

@HostListener('window:scroll', ['$event']) getScrollHeight(event) {
   console.log(window.pageYOffset, event);
}

如果你制作一个StackBlitz的例子会更好一个angular的设计稍微过度的例子,尽管你是一个救生员,谢谢你!fromEvent是一种rxjs方法,它将一个事件转化为一个可观察的序列:我花了3个小时找到一个有效的解决方案。枪友。Appreciated@AaronMatthews高兴:)这是一个指令,对吗?我只是把它添加到我需要听的元素中吗?我试过这样做,但以“窗口:滚动”作为事件,它并没有得到倾听。我是否将其添加到app.component.html本身?