Angular 7 scroll event does not fire

╄→尐↘猪︶ㄣ 提交于 2020-12-28 07:53:26

问题


For implementing a spy nav bar in my Angular app in a MatDialog component. I implemented a directive to spy for the scroll event using

@HostListener('window:scroll', ['$event'])

I also tried 'scroll' as event name. But the event does not seem to fire. I tried several approaches, e. g. by using the HostListener directly in the dialog component, by using the JavaScript window.onscroll() function and the rxjs fromEvent() function but without success.

Trying other css events (e. g. window:click) work fine. I also tried it in a "normal" component that is not displayed as a dialog but the event is not fired there either.

What could be the cause of this behaviour?


回答1:


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



回答2:


The reason for this behaviour is that angular material blocks the scroll event.

I solved it like this:

  ngAfterViewInit(): void {

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

    scroll$.subscribe(element => {
      // do whatever
    });
  }



回答3:


Try this...No need to do anything with html.

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

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


来源:https://stackoverflow.com/questions/53188426/angular-7-scroll-event-does-not-fire

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!