Angular 6 track scroll position of div within div

15,306

Solution 1

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

Solution 2

if you just need to scroll down add this to your div

 #scrollMe [scrollTop]="scrollMe.scrollHeight"

   <div class="my-list" #scrollMe [scrollTop]="scrollMe.scrollHeight">
   </div>
Share:
15,306
user3024827
Author by

user3024827

Updated on June 05, 2022

Comments

  • user3024827
    user3024827 4 months

    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?

  • user3024827
    user3024827 almost 4 years
    Fantastic - thank you for such a detailed answer! much help
  • Tantelope
    Tantelope almost 2 years
    Event.srcElement is now deprecated; use Event.target instead.