Skip to content
Advertisement

Angular – Scroll Event only page scroll

I need to check scroll event for a “show more” features.

Im using:

window.addEventListener('scroll', this.scroll, true);

and this code:

scroll = (event: any): void => {
        const number = event.srcElement.scrollTop;

        this.show_scroll_top = false;
        if (event.target.scrollTop >= 500) {
            this.show_scroll_top = true;
        }

        if (event.target.offsetHeight + event.target.scrollTop >= event.target.scrollHeight) {
              this.showMorFunctionFoo();
        }

    };

Unfortunally the scroll listen to every scroll in page, for example a scroll inside a DropDown etc…

How can I listen ONLY the PAGE scroll ignoring everyelse?

Advertisement

Answer

One solution might be to use hostListener from Angular (https://angular.io/api/core/HostListener) in your page component

@HostListener('scroll', ['$event']) 
onScroll($event:Event):void {
   ... your logic here
};

or you could use something like that

scroll = (event: any): void => {
    if (event.target.getAttribute('id') === YOU_PAGE_HTML_ID) {
       ... your logic here
    } 
};
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement