Sub topic 12
Running frequent events outside the Angular zone
This chapter assumes you know how Zone.js triggers change detection, how the Default and OnPush strategies work, and how setTimeout and DOM event callbacks behave in Angular components.
Why frequent events cost you
In the default setup, Zone.js patches browser APIs such as addEventListener and setTimeout. After each patched callback finishes, NgZone tells Angular to run change detection from the root. This is useful for clicks and HTTP responses. It is wasteful for events that fire dozens of times per second, such as mousemove, scroll, pointermove and requestAnimationFrame loops.
If a mousemove listener only records a coordinate, Angular still walks the component tree after every event. Nothing on screen changed, so the work is wasted. With a large tree, it can make the page feel slow.
Registering listeners outside the zone
NgZone.runOutsideAngular() runs a function in the parent zone. Any listener or timer created inside it is not tracked by Angular, so its callbacks do not start change detection.
import { Component, NgZone, OnDestroy, inject } from '@angular/core';
@Component({
selector: 'app-tracker',
template: `<p>Clicks recorded: {{ clicks }}</p>`,
})
export class Tracker implements OnDestroy {
private zone = inject(NgZone);
clicks = 0;
private onMove = () => {
// Runs outside the Angular zone, so it does not trigger change detection.
};
private onClick = () => {
this.zone.run(() => {
this.clicks++; // Re-enter the zone so Angular checks the view.
});
};
constructor() {
this.zone.runOutsideAngular(() => {
window.addEventListener('mousemove', this.onMove);
window.addEventListener('click', this.onClick);
});
}
ngOnDestroy() {
window.removeEventListener('mousemove', this.onMove);
window.removeEventListener('click', this.onClick);
}
}The listeners are registered inside runOutsideAngular, so mousemove never triggers a check. The click handler calls this.zone.run() because it changes clicks, which the template displays. Code inside run executes in the Angular zone. When it finishes, Angular runs change detection.
Rules to follow
- Register the listener outside the zone. Calling
runOutsideAngularinside the callback is too late, because the zone already notified Angular. - Re-enter the zone only when the view needs an update. Throttle those updates if the event is frequent.
- Remove the listeners in
ngOnDestroy. Listeners added towindowordocumentoutlive the component otherwise. - Keep the same function reference for
addEventListenerandremoveEventListener. This is why the example uses arrow function properties.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| The view does not update after an event | The handler changed state outside the zone and never re-entered | Wrap the state change in `zone.run()`, or use a signal or `markForCheck()` |
| Change detection still runs on every event | The listener was registered inside the zone, for example with a template `(mousemove)` binding | Register it manually in `runOutsideAngular` |
| Memory grows after navigating | Listeners on `window` were never removed | Remove them in `ngOnDestroy` |
Template event bindings such as (mousemove)="..." always run inside the zone. For high-frequency events, use manual registration as shown above.
Exercise
A component registers a scroll listener with window.addEventListener inside runOutsideAngular. The handler updates a plain offset field that the template shows, but the page never changes. Give two ways to fix it.
Show answer
The handler changes state outside the Angular zone, so nothing schedules a check. Either wrap the assignment in this.zone.run(() => { this.offset = ... }), or store the value in a signal that the template reads, so the signal update schedules the check. Calling markForCheck() also works for an OnPush component, but only when a check is going to run. Throttling the update, for example with requestAnimationFrame, avoids checking on every scroll event.