The use of Angular HostListeners can lead to performance issues, especially when the host component has many of them targeting the window or document object. This scenario triggers the Angular Change Detection more frequently than necessary, potentially slowing down applications.
It is therefore advisable to use ngZone to control the execution of code outside the Angular Change Detection.
Here is an example of how to capture a scroll event by calling the ngZone.runOutsideAngular()
method to turn off Angular Change Detection, and using ngZone.run()
to manually trigger it when necessary:
1@Component({
2 ...
3})
4export class InfiniteScrollComponent implements OnDestroy {
5 private readonly ngZone = inject(NgZone);
6 private readonly destroy$ = new Subject<void>();
7
8 constructor() {
9 this.ngZone.runOutsideAngular(() => {
10 fromEvent(document, 'scroll')
11 .pipe(takeUntil(this.destroy$))
12 .subscribe((e: Event) => {
13 this.ngZone.run(() => {
14 this.calculatePageOnScroll(e);
15 });
16 });
17 });
18 }
19
20 ngOnDestroy() {
21 this.destroy$.next();
22 this.destroy$.complete();
23 }
24
25 private calculatePageOnScroll(e: Event): void {
26 // do the calculation here
27 }
28}
29
In the above example, the Angular application doesn't perform Change Detection, allowing you to manage when it happens with the ngZone.run()
method within the subscription.