How to get on scroll events?

后端 未结 4 1161
礼貌的吻别
礼貌的吻别 2020-12-24 10:31

I need to get scroll events from a div with overflow: scroll in my Angular 2 app.

It seems onscroll event do not works on Angular 2.

How could I achieve that

相关标签:
4条回答
  • 2020-12-24 10:49

    You could use a @HostListener decorator. Works with Angular 4 and up.

    import { HostListener } from '@angular/core';
    
    @HostListener("window:scroll", []) onWindowScroll() {
        // do some stuff here when the window is scrolled
        const verticalOffset = window.pageYOffset 
              || document.documentElement.scrollTop 
              || document.body.scrollTop || 0;
    }
    
    0 讨论(0)
  • 2020-12-24 11:02

    Listen to window:scroll event for window/document level scrolling and element's scroll event for element level scrolling.

    window:scroll

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

    or

    <div (window:scroll)="onWindowScroll($event)">
    

    scroll

    @HostListener('scroll', ['$event'])
    onElementScroll($event) {
    
    }
    

    or

    <div (scroll)="onElementScroll($event)">
    

    @HostListener('scroll', ['$event']) won't work if the host element itself is not scroll-able.

    Examples

    • Using Event Binding
    • Using HostListener
    0 讨论(0)
  • 2020-12-24 11:04

    for angular 4, the working solution was to do inside the component

    @HostListener('window:scroll', ['$event']) onScrollEvent($event){
      console.log($event);
      console.log("scrolling");
    } 
    
    0 讨论(0)
  • 2020-12-24 11:13
    // @HostListener('scroll', ['$event']) // for scroll events of the current element
    @HostListener('window:scroll', ['$event']) // for window scroll events
    onScroll(event) {
      ...
    }
    

    or

    <div (scroll)="onScroll($event)"></div>
    
    0 讨论(0)
提交回复
热议问题