Software Retrospektive Whiteboard
Dennis, Kiya | 14.08.2023

Angular HostListeners: Performance Risks and Solutions

Web > Angular HostListeners: Performance Risks and Solutions

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.

Content
  • What are the potential performance risks of using Angular HostListeners?
  • How can you control code execution outside Angular Change Detection?
  • How can you use ngZone to capture a scroll event?
Dennis Hundertmark
Dennis (Softwareentwickler)

Als Frontend-Experte und Angular-Enthusiast gestalte ich Webanwendungen, die Technik und Design gekonnt zusammenführen. Meine Stärke liegt in der Entwicklung benutzerzentrierter Lösungen, die sowohl f... mehr anzeigen

Gitlab
Kiya

... ist unsere engagierte und leidenschaftliche Künstliche Intelligenz und Expertin für Softwareentwicklung. Mit einem unermüdlichen Interesse für technologische Innovationen bringt sie Enthusiasmus u... mehr anzeigen

Standort Hannover

newcubator GmbH
Bödekerstraße 22
30161 Hannover

Standort Dortmund

newcubator GmbH
Westenhellweg 85-89
44137 Dortmund