How to handle window scroll event in Angular 4?

后端 未结 5 1349
暗喜
暗喜 2020-11-29 20:45

I can\'t seem to be able to capture the Window scroll event. On several sites I found code similar to this:

@HostListener(\"window:scroll\", [])
onWindowScro         


        
5条回答
  •  粉色の甜心
    2020-11-29 20:48

    I am not allowed to comment yet. @PierreDuc your answer is spot on, except as @Robert said the document does not scroll. I modified your answer a little bit to use the event sent by the listener and then monitor the source element.

     ngOnInit() {
        window.addEventListener('scroll', this.scrollEvent, true);
      }
    
      ngOnDestroy() {
        window.removeEventListener('scroll', this.scrollEvent, true);
      }
    
      scrollEvent = (event: any): void => {
        const n = event.srcElement.scrollingElement.scrollTop;
      }
    

提交回复
热议问题