72

Is there an easy way to track the browser scroll position and notify more than a single component about it?

Use case: On scroll I want to be able to change classes of various elements on the page based upon where I am. In a previous version of angular it was somewhat possible through a plugin (same for jQuery). Of course, there is the option of writing bare JS to initialize it on application start and emit an event, but that sounds dirty, and event emission is pretty expensive for this type of thing.

What are my options here?


UPDATE (after suggestions):

Here is what I tried:

I created a component:

import {Component} from "angular2/core";

@Component({
    selector: '[track-scroll]',
    host: {'(window:scroll)': 'track($event)'},
    template: ''
})

export class TrackScrollComponent {
    track($event) {
        console.debug("Scroll Event", $event);
    }
}

added an attribute to the main directive of an app:

<priz-app track-scroll>

and added the component as one of the providers in the top component:

import {TrackScrollComponent} from "../../shared/components/track-scroll.component";

@Component({
  selector: 'priz-app',
  moduleId: module.id,
  templateUrl: './app.component.html',
  directives: [ROUTER_DIRECTIVES, SecureRouterOutlet, AppHeader, TrackScrollComponent],
  providers: [AuthenticationService]
})

Still nothing...


ANOTHER UPDATE:

Moved track-scroll to one of the div elements of the main template:

<div class="container-fluid" track-scroll>
    <div class="row">
        <div class="col-md-12">
            <app-header></app-header>
            <secure-outlet signin="Login" unauthorized="AccessDenied"></secure-outlet>
        </div>
    </div>
</div>

And now the app loads with a completely empty screen. FUN FUN FUN...


FINAL SOLUTION (that worked for me).

  1. Define a directive:
import {Directive} from "angular2/core";

@Directive({
    selector: '[track-scroll]',
    host: {'(window:scroll)': 'track($event)'}
})

export class TrackScrollDirective {
    track($event: Event) {
        console.debug("Scroll Event", $event);
    }
}
  1. Add it as a directive everywhere that uses it:
directives: [TrackScrollDirective]
  1. Add the attribute to each element we want to track the event:
<div class="col-md-12" track-scroll>
5
  • 1
    Next question is, what is the best way to propagate that to another component? Apr 7, 2016 at 8:02
  • 1
    Not sure what you mean by propagate? You can just emit using an @Output() and bind it to an @Input() of another component. I added a comment to my answer about directives: [...]. Apr 7, 2016 at 8:04
  • Basically, I want to use this information in other component. Do I have to do it through EventEmitter? Apr 7, 2016 at 8:19
  • Yes, you can use @Output() scrollPos:EventEmitter and @Input() scrollPos on the receiving component and bind in the template if they are parent-child. Apr 7, 2016 at 9:17
  • Opened separate question for this: stackoverflow.com/questions/36471927/… Apr 7, 2016 at 9:27

5 Answers 5

88

I think the easiest way is each interested component listening to the scroll event.

  @Component({
    ...
    // alternative to `@HostListener(...)`
    // host: {'(window:scroll)': 'doSomething($event)'}
  })
  class SomeComponent {
    @HostListener('window:scroll', ['$event']) 
    doSomething(event) {
      // console.debug("Scroll Event", document.body.scrollTop);
      // see András Szepesházi's comment below
      console.debug("Scroll Event", window.pageYOffset );
    }
  }

plunker

Plunker using @HostListener()

Hint:

bootstrap(MyComponent, [
    provide(PLATFORM_DIRECTIVES, {useValue: [TrackScrollDirective], multi:true})]);

makes the directive universal without adding it to every components directive: [...] list.

12
14

I was forced to solve this differently because I needed to watch several scrolling elements on the window. I created a directive to watch the scroll position on an element:

@Directive({
  selector: '[scroll]'
})
export class ScrollDir {
  @Output() setScroll = new EventEmitter();
  private scroll: number;

  constructor(private el: ElementRef) { }

  @HostListener('scroll', ['$event'])
  scrollIt() { this.scroll = event.srcElement.scrollTop }

  reset() {  this.el.nativeElement.scrollTop = this.scroll }
}

Then on any any component containing a scroll element that needed this element I could @ViewChild the directive like this:

@Component({
  selector: 'parent',
  template: `
    <div class="container" scroll>
      // *ngFor=""...
    </div>
  `
})
export class ParentComp implements AfterViewChecked {

  @ViewChild(ScrollDir) scroll: ScrollDir;

  ngAfterViewChecked() {
    this.scroll.reset()
  }
}
1
  • This is the correct answer for those who are looking for scroll event inside a DOM element that is not the window. In my case, I am tracking the scroll of a <div> nested down the DOM tree. event.srcElement.scrollTop works like a charm Nov 4, 2020 at 17:56
11

Look at the source to ScrollService, as part of the angular documentation project.

The way they get the position is fromEvent(window, 'scroll')

You can then do something like this in a global service you inject into your component:

public readonly windowScroll$ = fromEvent(window, 'scroll').pipe(map(x => window.scrollY), startWith(0), distinctUntilChanged(), shareReplay(1));

The startWith(0) is needed because you may not get a scroll event until you actually scroll. You can add debouncing if needed.

0
4

I had a similar problem, i needed to scroll a div when user scroll a page, and solved my problem with the code below. At the component where you want to capture the scroll:

import { HostListener } from '@angular/core';

@ViewChild('curtain') divCurtain: ElementRef;

export class ComponentX {
    @HostListener('window:scroll', ['$event']) onScrollEvent($event) {
        console.log(window.pageYOffset);
        this.divCurtain.nativeElement.style.top = window.pageYOffset.toString().concat('px');
    }

    ngOnInit(): void { }
}

Only this, i did not create any directive or other code. This HostListener is executed every time the user scroll the page, and i get the window.pageYOffset to send to my div.

I hope it helps.

0

In angular we can track the scroll position inside a div using viewchild events.

First add a reference in html

<div #postion class="scroll-container">
  .......
  .......
</div>

Declare the ref in ts file using viewchild

@ViewChild('postion', { static: true }) _div: ElementRef;

Then inside ngAfterViewInit function

 ngAfterViewInit() {
     fromEvent(this._div?.nativeElement, 'scroll').subscribe((e: any) =>  {
         this.scrollPosition = e?.target['scrollTop'];
            });
  }
 

Import fromEvent from rxjs.

And If you want to scroll to this saved position later, then you can do

      (this._div.nativeElement as HTMLElement).scrollTop = this.scrollPosition;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.