Tracking scroll position and notifying other components about it

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

    // 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 using @HostListener()


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

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

Leave a Comment