Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 6 track scroll position of div within div

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?

like image 873
user3024827 Avatar asked Oct 31 '25 01:10

user3024827


1 Answers

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

like image 145
Alex K Avatar answered Nov 03 '25 00:11

Alex K