Sub topic 12
Running frequent events outside the Angular zone
This chapter assumes you know how Zone.js starts a change detection cycle (covered earlier in this tutorial), what NgZone is, and how the default and OnPush strategies decide which components to check. It also assumes you are comfortable with addEventListener, setTimeout, and requestAnimationFrame.
Why frequent events are a problem
In the default setup, Zone.js patches browser APIs such as addEventListener, setTimeout, setInterval, promises, and requestAnimationFrame. When a callback registered in the Angular zone finishes, NgZone emits onMicrotaskEmpty. Angular then runs change detection from the root of the tree.
This is convenient for most code. It is costly for events that fire dozens or hundreds of times per second, such as mousemove, scroll, pointermove, resize, and requestAnimationFrame loops. Each callback triggers a full pass over every component that is checked under the current strategy. If the handler only updates a canvas or logs a coordinate, that pass produces no DOM change and is wasted work.
The fix is to register those listeners outside the Angular zone. Callbacks that run there still execute, but Zone.js does not notify Angular when they finish, so no change detection starts.
The two methods you need
NgZone provides two methods for moving between zones:
| Method | What it does | Typical use |
|---|---|---|
| `runOutsideAngular(fn)` | Runs `fn` in the parent zone. Async work scheduled inside it stays outside the Angular zone. | Registering listeners and timers that should not trigger change detection. |
| `run(fn)` | Runs `fn` inside the Angular zone. When it finishes, Angular runs change detection. | Reporting a result back to the view. |
The key point is that the zone is captured when a callback is registered, not when it fires. A listener added inside runOutsideAngular stays outside the Angular zone every time it is called.
A worked example
The component below listens to mousemove and click on window. The mousemove handler fires constantly and does not touch the view. The click handler changes clicks, which is displayed in the template.
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);
}
}Three details matter here.
- Both listeners are registered inside
runOutsideAngular, so neither starts change detection on its own. - The click handler calls
zone.runonly at the moment the view must change. Angular runs one cycle whenrunreturns. - The handlers are stored as arrow-function properties.
removeEventListenerneeds the same function reference that was passed toaddEventListener, so an inline arrow function would leak the listener.
The flow of a mousemove event and a click event differs as follows.
Using it with OnPush and manual updates
Leaving the zone does not replace the other update mechanisms. It only removes the automatic trigger. If a callback outside the zone changes state that the template shows, you need one of these:
- Call
zone.runaround the state change, as above. - Call
ChangeDetectorRef.markForCheck()(for OnPush components) and make sure a cycle will run afterwards. Marking alone does not start a cycle. If nothing else triggers one, the view stays stale. - Call
ChangeDetectorRef.detectChanges()to check this component and its children immediately. - Write to a signal read by the template. Signal updates schedule a check without relying on the zone.
Choose zone.run when you want the standard behavior of a full cycle. Choose detectChanges() when you want to update a single component without checking the rest of the tree.
Throttling instead of leaving the zone
Sometimes you do need to update the view often, but not on every event. A common pattern is to do the cheap work outside the zone and re-enter only when a value crosses a threshold or at a fixed rate.
import { Component, NgZone, OnDestroy, inject } from '@angular/core';
@Component({
selector: 'app-scroll-progress',
template: `<p>Scrolled: {{ percent }}%</p>`,
})
export class ScrollProgress implements OnDestroy {
private zone = inject(NgZone);
percent = 0;
private frame = 0;
private onScroll = () => {
if (this.frame) {
return; // a frame is already scheduled
}
this.frame = requestAnimationFrame(() => {
this.frame = 0;
const doc = document.documentElement;
const max = doc.scrollHeight - doc.clientHeight;
const next = max > 0 ? Math.round((doc.scrollTop / max) * 100) : 0;
if (next !== this.percent) {
this.zone.run(() => {
this.percent = next;
});
}
});
};
constructor() {
this.zone.runOutsideAngular(() => {
window.addEventListener('scroll', this.onScroll, { passive: true });
});
}
ngOnDestroy() {
window.removeEventListener('scroll', this.onScroll);
if (this.frame) {
cancelAnimationFrame(this.frame);
}
}
}The scroll handler runs outside the zone and coalesces events into at most one requestAnimationFrame callback per frame. It enters the zone only when the rounded percentage actually changes. A page scrolled from top to bottom triggers at most 100 change detection runs, regardless of how many scroll events the browser fires.
Edge cases and common mistakes
- Registering inside the zone by accident. If you add a listener in a lifecycle hook that already runs inside the Angular zone, wrap the registration in
runOutsideAngular. Registering outside the wrapper puts the listener in the Angular zone permanently. - Third-party libraries. Libraries that start timers or listeners in their initialization code (charts, maps, drag-and-drop) can cause many cycles. Call their setup function inside
runOutsideAngular. When the library invokes a callback you supplied and you need to update the view, wrap the state change inzone.run. - Template event bindings. A
(mousemove)="..."binding in a template is registered by Angular inside the zone. To avoid that cost, useaddEventListenerin code, as in the examples. - Forgetting cleanup. Listeners outside the zone are not tracked by Angular. Remove them in
ngOnDestroy, or useDestroyRef.onDestroy, or anAbortSignalpassed in the listener options. - Promises and
asyncfunctions. Zone.js tracks promise continuations through the zone captured at the time the promise callback is registered. Awaiting insiderunOutsideAngularkeeps later steps outside the zone, but state changes there still need an explicit re-entry to show up in the view. - Unit tests.
fixture.detectChanges()runs a check regardless of zone, so a test can pass while the real app shows stale data. Test the path where the event fires and assert that the DOM updates after the event. - Zoneless applications. Without Zone.js there is no automatic trigger to opt out of, so
runOutsideAngularhas no effect on scheduling. Updates come from signals,markForCheck, template events, and similar notifications. The throttling idea still applies: write to a signal only when the value changes.
When to use it
Use runOutsideAngular when all of these are true:
- The event fires many times per second or runs continuously, as with animation loops, polling timers, and pointer tracking.
- Most invocations do not change anything the template displays.
- You can identify the few moments when the view must be updated.
Do not use it for ordinary click handlers, form input, or HTTP responses. Those fire rarely, and the standard behavior is simpler and less error-prone. Adding zone management there makes the code harder to read without a measurable gain.
Exercise
A component registers window.addEventListener('resize', this.onResize) inside runOutsideAngular. The handler sets this.width = window.innerWidth, and the template shows {{ width }}. The component uses the Default strategy. After resizing the window, the number in the page never changes. Why, and what is the smallest fix?
Show answer
The listener was registered outside the Angular zone, so when it finishes Zone.js does not notify Angular and no change detection runs. The field is updated, but the DOM is not. The smallest fix is to wrap the assignment in this.zone.run(() => { this.width = window.innerWidth; }). Throttling the update with requestAnimationFrame, or changing width into a signal, would also work and would limit the number of cycles.
Exercise
Why does the Tracker example store onMove and onClick as arrow-function properties instead of passing inline arrow functions to addEventListener?
Show answer
removeEventListener only removes a listener when it receives the same function reference that was added. Inline arrow functions create a new reference that cannot be passed again in ngOnDestroy, so the listeners would stay on window after the component is destroyed. That leaks memory and keeps running the handler.