doe
doe

Reputation: 455

Getting the scroll position for an Angular component

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) {
  ...
}

Upvotes: 3

Views: 12101

Answers (1)

julianobrasil
julianobrasil

Reputation: 9357

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.

Upvotes: 6

Related Questions