Home > Mobile >  Angular - window:scroll Event - Get specific scrollbar (Page has multiple scrollbars)
Angular - window:scroll Event - Get specific scrollbar (Page has multiple scrollbars)

Time:10-24

I don't know how to get a specific scrollbar from a component. My page has multiple scrollbars and I want to use a specific scrollbar and change its position (scrollTop).

I implemented this code in the child component that displays one scrollbar in a div (print screen below):

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

But for some reason, this event is triggering only if I change scrollbar position in the parent component.

enter image description here

CodePudding user response:

As far as I know, each element has its own scroll event to fire and listen to. When you listen to the window:scroll event you are just listening to the window scroll event but not that specific element.

To get access to the scrollTop of an element in angular, you can get the dom element by referece using the @ViewChild() decorator like this:

First you need to use a template variable to give the element an angular identifer

<div #scrollElement style="overflow-y=scroll"></div>

In your component you can reference your scroll element:

@ViewChild('scrollElement', {use: ElementRef}) private childEl: ElementRef;

And then access and set the scrollTop property in your method:

setScrollTop() {
  this.childEl.navtiveElement.scrollTop = 50;
}

Here is a Stackblitz example

  • Related