Sub topic 3
How Zone.js tells Angular something may have changed
This chapter assumes you know Angular components and templates, TypeScript classes, and template binding syntax. It also assumes you are comfortable with setTimeout and promises. It explains how Angular finds out that something may have changed, so it knows when to run change detection.
The problem Zone.js solves
Angular does not watch your fields. When you write this.count++ in a click handler, nothing in plain JavaScript tells Angular that the value changed. Angular needs an outside signal that says "some code just ran, so the view may be out of date."
In the default setup, that signal comes from Zone.js. Zone.js is a library that patches browser asynchronous APIs. It lets Angular know when asynchronous work starts and when it finishes. Angular then runs a change detection cycle after that work ends.
Zone.js does not know what changed. It only knows that code ran. This is why the chapter title says "may have changed."
What a zone is
A zone is an execution context that follows asynchronous work. When code is scheduled inside a zone, such as with setTimeout, the callback later runs in the same zone. The zone can run hooks before and after the callback.
Zone.js achieves this by monkey patching. At startup it replaces browser APIs with wrapped versions that remember the current zone. The patched APIs include:
- Timers:
setTimeout,setInterval,requestAnimationFrame. - Event listeners added with
addEventListener. - Promises, including
thencallbacks. XMLHttpRequest, andfetchthrough its promise.
Angular creates a zone called the Angular zone, represented by the NgZone service. Your component code normally runs inside it.
From a task to a check
Zone.js groups work into tasks. A task is one callback invocation, such as one timer firing or one click handler call. Angular's NgZone listens to zone hooks and tracks when the zone becomes stable or unstable.
The flow for a click looks like this:
- The browser fires a click event.
- The patched listener runs your handler inside the Angular zone.
- Your handler changes component state.
- The handler returns, and the zone sees that no synchronous work is left in the task.
NgZoneemitsonMicrotaskEmpty.- Angular subscribes to that event and runs change detection from the root.
The check starts at the root and visits the component tree. The next chapter covers that walk. For now, the key point is that the trigger and the check are separate. Zone.js only supplies the trigger.
Seeing it in code
The following component changes state in three different asynchronous ways. Under Zone.js, all three cause a view update with no extra code.
import { Component } from '@angular/core';
@Component({
selector: 'app-zone-demo',
template: `
<p>Timer: {{ timer }}</p>
<p>Promise: {{ promise }}</p>
<button (click)="clicks = clicks + 1">Clicks: {{ clicks }}</button>
`,
})
export class ZoneDemo {
timer = 'waiting';
promise = 'waiting';
clicks = 0;
constructor() {
setTimeout(() => {
this.timer = 'fired after 1 second';
}, 1000);
Promise.resolve().then(() => {
this.promise = 'resolved';
});
}
}Neither the timer callback nor the promise callback calls any Angular API. The view still updates because both callbacks run inside the Angular zone. After each one finishes, NgZone reports that the zone is stable and Angular checks the tree.
What does and does not trigger a check
The trigger is any task that finishes inside the Angular zone. Common sources are:
| Source | Triggers a check under Zone.js |
|---|---|
| DOM event listener in a template, such as `(click)` | Yes |
| `setTimeout` or `setInterval` callback | Yes |
| Promise `then` callback | Yes |
| HTTP response through `HttpClient` | Yes |
| Callback registered inside `runOutsideAngular` | No |
| Code in a Web Worker | No |
| Change made with no asynchronous task, such as a direct call from the console | No |
Two points are easy to miss. First, a check runs after every task, even when the task changed nothing. A handler that only logs to the console still starts a full cycle under the Default strategy. Second, the number of checks follows the number of tasks, not the number of state changes. Ten timer callbacks in one second mean ten checks.
Why the Default setup can be expensive
Every task in the Angular zone runs a check of the whole component tree, from the root downward, unless a component uses OnPush. A later chapter covers that cost in detail. Zone.js adds to it in a particular way: it triggers checks for work you do not control.
Typical examples:
- A
mousemoveorscrolllistener that fires dozens of times per second. - A third-party chart or map library that registers its own timers and listeners.
- A polling loop with
setIntervalthat updates something outside the template.
Each of these runs a full check even when the data shown on screen is the same. Because Zone.js cannot tell which tasks matter, it reports all of them.
Controlling the zone with NgZone
The NgZone service gives you two methods that control where code runs.
runOutsideAngular(fn)runsfnin the parent zone. Tasks started there do not trigger a check when they finish.run(fn)runsfninside the Angular zone. A check follows when it finishes.
A common pattern is to register a frequent listener outside the zone, then call run only when the view needs to update. This tutorial's later chapter on running code outside the zone covers this in full. Here is the shape of it:
import { Component, NgZone, OnDestroy, inject } from '@angular/core';
@Component({
selector: 'app-scroll-watcher',
template: `<p>Reached bottom: {{ reachedBottom }}</p>`,
})
export class ScrollWatcher implements OnDestroy {
private zone = inject(NgZone);
reachedBottom = false;
private onScroll = () => {
const atBottom =
window.innerHeight + window.scrollY >= document.body.scrollHeight;
if (atBottom !== this.reachedBottom) {
this.zone.run(() => {
this.reachedBottom = atBottom;
});
}
};
constructor() {
this.zone.runOutsideAngular(() => {
window.addEventListener('scroll', this.onScroll);
});
}
ngOnDestroy() {
window.removeEventListener('scroll', this.onScroll);
}
}The scroll listener fires many times, but a check runs only when reachedBottom flips.
Common errors and gotchas
- View does not update after third-party code. A library that registers its listeners outside the Angular zone changes your state without a trigger. Wrap the state change in
zone.run, or callChangeDetectorRef.markForCheckin an OnPush component. - Checks run constantly. A timer, a polling loop or a frequent listener inside the zone keeps scheduling checks. Move it into
runOutsideAngular. - Tests hang or behave oddly. Pending timers keep the zone unstable. Test helpers such as
fakeAsyncandwhenStablerely on zone tracking. - Native
async/awaitis not patched. Zone.js cannot intercept nativeasyncfunctions, so the Angular CLI compiles them down to promise-based code when Zone.js is in use. If you disable that downleveling, zone tracking can break. - Zone.js is optional. Angular can run without it, and then you must tell Angular about changes yourself, for example with signals. A later chapter covers that setup.
Summary of the mechanism
Zone.js patches browser asynchronous APIs at startup. Code in the Angular zone is tracked task by task. When a task ends and no microtasks remain, NgZone emits onMicrotaskEmpty, and Angular runs change detection from the root. The trigger is coarse, so reducing work means either limiting which tasks run inside the zone or limiting which components each check visits.
Exercise
A component registers a mousemove listener inside NgZone.runOutsideAngular and increments a moves field in it. The template shows {{ moves }}. The count on screen stays at 0 while the mouse moves. Why, and how can you update the view at most once per second without checking the tree on every move?
Show answer
The listener runs outside the Angular zone, so its tasks never cause onMicrotaskEmpty and Angular never runs a check. The field changes, but the DOM is not updated. To refresh once per second, keep counting outside the zone and start a setInterval inside runOutsideAngular that calls this.zone.run(() => { this.shown = this.moves; }) each second. Bind the template to shown. Only the run call triggers a check, so the tree is checked once per second instead of on every mouse move.
Exercise
A click handler runs console.log('clicked') and nothing else. Under Zone.js with the Default strategy, does Angular run change detection after it, and why?
Show answer
Yes. Zone.js reports that a task finished in the Angular zone but cannot tell what the handler changed. Angular therefore runs a check from the root after every such task, even when no state changed.