Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the scroll position for an Angular component

Tags:

angular

How can I get the scroll position with a component with fromEvent?

I use this to get mouse position, how do I get scroll from top position?

this.mouseMoveSubscription = fromEvent(this.elementRef.nativeElement, 'mousemove')
                  .subscribe((e: MouseEvent) => {...});

This doesn't work:

ngOnInit() {
    this.scrollSubscription = fromEvent(this.elementRef.nativeElement, 'scroll')
                  .subscribe((e: Scroll) => {
                    console.log(e.position);
                  });

  }

No events are firing for this either (from: answer):

@HostListener('scroll', ['$event']) // for scroll events of the current element
onScroll(event) {
  ...
}
like image 744
doe Avatar asked Aug 09 '26 13:08

doe


1 Answers

It seems you're just looking for the position in the wrong event attribute.

fromEvent(this.elementRef.nativeElement,'scroll')
      .subscribe((e: Event) => console.log({
        scrollPosition: e.target['scrollTop']
        }));

Take a look at this demo.

like image 140
julianobrasil Avatar answered Aug 11 '26 08:08

julianobrasil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!