Angular 4 @HostListener Window scroll event strangely does not work in Firefox
try this:
@HostListener('window:scroll', ['$event'])
onWindowScroll($event) {
console.log("scrolling...");
}
I prefer this:
this.eventSubscription = Observable.fromEvent(window, "scroll").subscribe(e => {
this.onWindowScroll();
});
This Angular directive will work in both Chrome and Firefox:
import { Directive, Output, EventEmitter, HostListener, ElementRef, OnDestroy
} from '@angular/core';
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/observable/fromEvent';
@Directive({
selector: '[scroll]'
})
export class ScrollEventDirective implements OnDestroy {
@Output() scrollPosition: EventEmitter<number> = new EventEmitter<number>
();
private scrollEvent$;
constructor(private el: ElementRef) {
this.scrollEvent$ = Observable.fromEvent(this.el.nativeElement,
'scroll').subscribe((e: any) => {
this.scrollPosition.emit(e.target.scrollTop);
});
}
ngOnDestroy() {
this.scrollEvent$.unsubscribe();
}
}
Using the directive on a DIV element:
<div scroll (scrollPosition)="scrollChanged($event)">...</div>
How i solved this
Works perfectly on Firefox, chrome and other browsers
Concept: You can listen to the properties of scrolling element that is body for now if you don't have any other scrolling element
@HostListener('window:scroll', ['$event']) onWindowScroll(e) {
console.log(e.target['scrollingElement'].scrollTop)
// Your Code Here
}
I did face the same issue and resolved it by using window.scrollY rather than using this.document.body.scrollTop to make it work in Mozila Firefox. I know it is strange but it works.