HostListener slows down the application: Angular2

I have a hostListner that listens for a scroll event in my Angular2 application. I use it to check if the user scrolls to the bottom of the page and executes the method when the user reaches the bottom of the page. I created a hostlistner as follows:

  @HostListener('window:scroll', [])
  onWindowScroll() {
   const scrolledPercent = /* some logic to calculate the percentage scrolled */
  if ( condition1 && condition2 .... )
    { 
     // doing something here
    }
  }

But it slows down my application, but not very important, but scrolling on the page is not smooth. Maybe because the host is constantly looking for a page to scroll, so the subscription does the whole process of scrolling through the lag. I tried removing hostListner and the scroll became smooth again. Has anyone noticed this behavior? If not, what is the way to subscribe to the scroll event on the page using Angular2?

+4
source share
1

angular, .

EventManager, .

EVENT-manager.ts

import { Injectable, Inject, NgZone  } from '@angular/core';
import { EVENT_MANAGER_PLUGINS, EventManager } from '@angular/platform-browser';

@Injectable()
export class CustomEventManager extends EventManager {
  constructor(@Inject(EVENT_MANAGER_PLUGINS) plugins: any[], private zone: NgZone) {
    super(plugins, zone); 
  }    

  addGlobalEventListener(element: HTMLElement, eventName: string, handler: Function): Function {
    if(eventName.endsWith('out-zone')) {
      eventName = eventName.split('.')[0];
      return this.zone.runOutsideAngular(() => 
          super.addGlobalEventListener(element, eventName, handler));
    } 

    return super.addGlobalEventListener(element, eventName, handler);
  }
}

app.module.ts

  ...
  providers: [
    { provide: EventManager, useClass: CustomEventManager }
  ]
})
export class AppModule {}

changeDetector.detectChanges

@HostListener('window:scroll.out-zone', []) // notice out-zone
onWindowScroll() {
  const scrolledPercent = /* some logic to calculate the percentage scrolled   */
  if ( condition1 && condition2 .... ) { 
      this.cd.detectChanges();
  }
}

.

+7

Source: https://habr.com/ru/post/1681923/


All Articles