I am trying to create a directive that tracks the Y position of the element it is placed on - when this element reaches the top of the parent div, I will add sticky styling to make the header stick to the top until the whole element has been scrolled.
I have tried to track the scrolling, but can't get any output apart from the initial ngoninit log:
import { Directive, OnInit, ElementRef, HostBinding, HostListener } from '@angular/core';
@Directive({
    /* tslint:disable-next-line:directive-selector */
    selector: '[stickyHeaderDirective]'
})
export class StickyHeaderDirective implements OnInit {
    ngOnInit() {
        console.log('lets track ths scroll');
    }
    constructor() {}
    @HostListener('scroll', ['$event']) private onScroll($event: Event): void {
        console.log($event.srcElement.scrollLeft, $event.srcElement.scrollTop);
    }   
}
What am i missing?
HostListener only listens for scroll events which occur on the [stickyHeaderDirective] element. That element must be the one firing the scroll events.
Make sure the [stickyHeaderDirective] element has the correct CSS styling to allow it to scroll. Here's a demo showing the difference with and without CSS styles.
for (let element of document.getElementsByClassName('track-scrolling')) {
  element.addEventListener('scroll', e => {
      console.log(e.target.scrollLeft, e.target.scrollTop);
  });
}
.container {
  height: 200px;
  width: 200px;
  overflow: auto;
  margin: 10px;
  border: 1px solid;
}
.big-content {
  height: 1000px;
  width: 1000px;
}
.track-scrolling.wrong {
  /*
  No overflow property
  No height/width or max-height/width
  */
  color: red;
}
.track-scrolling.right {
  overflow: auto;
  max-height: 100%;
  
  color: green;
}
<div class="container">
  <div class="track-scrolling wrong">
  I won't fire scroll events
    <div class="big-content"></div>
  </div>
</div>
<div class="container">
  <div class="track-scrolling right">
  I will fire scroll events
    <div class="big-content"></div>
  </div>
</div>
And here's a demo showing the same behavior with your directive: https://stackblitz.com/edit/angular-kqvraz
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With