user3024827
user3024827

Reputation: 1258

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?

Upvotes: 4

Views: 20851

Answers (2)

alexhughesking
alexhughesking

Reputation: 2007

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

Upvotes: 3

Akitha_MJ
Akitha_MJ

Reputation: 4294

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>

Upvotes: 2

Related Questions