Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect scroll event from inner div

Tags:

angular

I want to be able to detect events when scrolling from a scrollable inner div not just a window target.

For example i have a Directive which listen for scroll events, here I need to change ' host: '(window:scroll)' to something else.

import {Directive, Output, EventEmitter} from '@angular/core';

@Directive({
  selector: '[infinite-scroll]',
  host: {'(window:scroll)': 'track($event)'},
})

export class InfiniteScrollerDirective {
  @Output() scrolled = new EventEmitter();

  track(event: Event) {
    this.scrolled.emit({
        value: event
    });
  }
}

I use it in my component as infinite-scroll directive with "scrolled" output.

<div infinite-scroll (scrolled)="onScroll($event.value)">
  <table class="table">
    <thead>
    </thead>
    <tbody>
    </tbody>
  </table>
</div>...

And event goes here.

 onScroll(event: UIEvent) {

 }
like image 266
Emanuel Weinsjö Avatar asked Jun 22 '16 14:06

Emanuel Weinsjö


People also ask

How can check scroll inside div?

scroll(function() { //detect page scroll if($(window). scrollTop() + $(window). height() == $(document). height()) //user scrolled to bottom of the page? { if(track_load <= total_groups && loading==false) //there's more data to load { loading = true; //prevent further ajax loading $('.

How does onScroll work?

Definition and Usage. The onscroll event occurs when an element's scrollbar is being scrolled. Tip: use the CSS overflow style property to create a scrollbar for an element.


1 Answers

I'm not sure why everyone here is trying to mess with the @HostListener. It is definitely required when working with page level events, but not child elements. Instead of going with JQuery style event binding, you can use Angular 2 event listeners. If you're working with an inner-div, all you need to do is add the scroll event listener on your div with a callback method like the following:

HTML:

<div (scroll)="onScroll($event)">

</div>

TypeScript:

onScroll(event): void {

    // Interpret the scroll event
    // Do stuff on inner div scroll
}
like image 78
I. Buchan Avatar answered Sep 21 '22 09:09

I. Buchan