Sub topic 14
Running high-frequency events outside the Angular zone
This chapter assumes you can read a Performance panel trace, know that Zone.js notifies Angular when async work finishes, and understand that change detection runs after that notification.
The problem: one event, one change detection pass
Zone.js patches browser APIs such as addEventListener and setTimeout. When a patched callback finishes, the Angular zone tells Angular to run change detection. This is convenient for clicks and HTTP responses. It is costly for events that fire dozens of times per second, such as scroll, mousemove, and resize.
In a trace, the symptom looks like a dense row of short tasks. Each task contains your small handler followed by a longer block of change detection work. The handler itself is cheap. The repeated change detection is the cost.
Confirm it in a trace first
Record while scrolling for a few seconds. Look for these signs:
- Many tasks, each tied to a
scrollevent. - A change detection call, such as
ApplicationRef.tick, after every handler. - Angular DevTools showing many change detection cycles with no visible template change.
If the handler does not change anything the view displays, the cycles are wasted work.
Register the listener outside the zone
NgZone.runOutsideAngular runs a function in the parent zone. Listeners registered there do not trigger change detection when they fire.
import { Component, NgZone, OnDestroy, OnInit, inject } from '@angular/core';
@Component({
selector: 'app-scroll-tracker',
template: `<ng-content />`,
})
export class ScrollTrackerComponent implements OnInit, OnDestroy {
private zone = inject(NgZone);
private onScroll = () => {
// Lightweight work that does not need to update the view.
};
ngOnInit() {
this.zone.runOutsideAngular(() => {
window.addEventListener('scroll', this.onScroll, { passive: true });
});
}
ngOnDestroy() {
window.removeEventListener('scroll', this.onScroll);
}
}Two details matter here. The passive: true option tells the browser the handler will not call preventDefault(), so scrolling does not wait on it. The ngOnDestroy cleanup removes the listener. Without it, the listener outlives the component, which shows up later as a leak in the Memory panel.
Re-entering the zone when the view must change
Sometimes the handler occasionally needs to update the UI, for example when the user scrolls past a threshold. Re-enter the zone only for that moment:
private onScroll = () => {
if (window.scrollY > 500 && !this.pastThreshold) {
this.zone.run(() => {
this.pastThreshold = true;
});
}
};This gives one change detection pass at the crossing, not one per event.
Verify the change
Record the same scroll gesture before and after. Compare the number of change detection calls and the total scripting time. If the numbers do not drop, the cycles came from another source.
Exercise
A mousemove listener registered with addEventListener inside ngOnInit produces a change detection pass on every event, but it only logs coordinates to an analytics buffer. What change fixes the wasted passes, and what must you also add to avoid a leak?
Show answer
Wrap the addEventListener call in this.zone.runOutsideAngular(...) so the event no longer notifies Angular. Also remove the listener in ngOnDestroy with removeEventListener, using the same function reference, so it does not outlive the component.