I need to get scroll events from a div with overflow: scroll in my Angular 2 app.
It seems onscroll event do not works on Angular 2.
How could I achieve that?
This question is related to
html
css
angular
typescript
scrollbar
Alternative to @HostListener
and scroll output on the element I would suggest using fromEvent from RxJS since you can chain it with filter()
and distinctUntilChanges()
and can easily skip flood of potentially redundant events (and change detections).
Here is a simple example:
// {static: true} can be omitted if you don't need this element/listener in ngOnInit
@ViewChild('elementId', {static: true}) el: ElementRef;
// ...
fromEvent(this.el.nativeElement, 'scroll')
.pipe(
// Is elementId scrolled for more than 50 from top?
map((e: Event) => (e.srcElement as Element).scrollTop > 50),
// Dispatch change only if result from map above is different from previous result
distinctUntilChanged());
for angular 4, the working solution was to do inside the component
@HostListener('window:scroll', ['$event']) onScrollEvent($event){
console.log($event);
console.log("scrolling");
}
Listen to window:scroll
event for window/document level scrolling and element's scroll
event for element level scrolling.
@HostListener('window:scroll', ['$event'])
onWindowScroll($event) {
}
or
<div (window:scroll)="onWindowScroll($event)">
@HostListener('scroll', ['$event'])
onElementScroll($event) {
}
or
<div (scroll)="onElementScroll($event)">
@HostListener('scroll', ['$event'])
won't work if the host element itself is not scroll-able.
You could use a @HostListener decorator. Works with Angular 4 and up.
import { HostListener } from '@angular/core';
@HostListener("window:scroll", []) onWindowScroll() {
// do some stuff here when the window is scrolled
const verticalOffset = window.pageYOffset
|| document.documentElement.scrollTop
|| document.body.scrollTop || 0;
}
Source: Stackoverflow.com