Angular 4 @HostListener Window scroll event strangely does not work in Firefox

前端 未结 4 1894
南笙
南笙 2020-12-06 02:16

I\'m using @HostListener(\'window:scroll\', []) in Angular 4 app in order to add additional class to the header on scrolling. It works fine in Chrome but I noti

相关标签:
4条回答
  • 2020-12-06 02:57

    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>
    
    0 讨论(0)
  • 2020-12-06 03:03

    try this:

    @HostListener('window:scroll', ['$event'])
    onWindowScroll($event) {
        console.log("scrolling...");
    }
    

    I prefer this:

    this.eventSubscription = Observable.fromEvent(window, "scroll").subscribe(e => {
                    this.onWindowScroll();
                });
    
    0 讨论(0)
  • 2020-12-06 03:04

    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
    
      }
    
    0 讨论(0)
  • 2020-12-06 03:14

    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.

    0 讨论(0)
提交回复
热议问题