Sub topic 1
How Angular learns that something may have changed
Prerequisites
This chapter assumes you can:
- Build Angular components with templates and data binding.
- Pass data through component inputs and outputs.
- Read basic RxJS code with Observables and subscriptions.
- Explain the difference between two variables pointing at the same object and two variables holding copies.
You do not need to know anything about OnPush yet. This chapter explains the mechanism that OnPush later narrows down.
The problem Angular has to solve
Angular templates read plain JavaScript values:
import { Component } from '@angular/core';
@Component({
selector: 'app-greeting',
template: `<p>Hello, {{ name }}</p>`,
})
export class GreetingComponent {
name = 'Ada';
rename() {
setTimeout(() => {
this.name = 'Grace';
}, 1000);
}
}The code assigns this.name = 'Grace' without calling any Angular API. JavaScript has no built-in way to notify a framework that a property changed. Yet the view updates. Angular needs two separate pieces of information to make that work:
- When to look. Some event has happened that could have changed data.
- What to look at. Which components must be re-evaluated.
This chapter covers the first piece. The rest of the tutorial covers the second, where OnPush makes the biggest difference.
Change detection is the process in which Angular compares the current values used in a template with the values it last rendered, and updates the DOM where they differ. Angular does not diff your data model. It re-evaluates the template expressions and compares their results with the previous results.
Zone.js: noticing asynchronous work
Almost every change to application state happens inside a callback. A user clicks, a timer fires, a Promise resolves, or an HTTP response arrives. If Angular knew when each callback finished, it could run change detection right after it.
Zone.js is a library that provides this knowledge. When your application loads, Zone.js replaces (patches) the browser's asynchronous APIs with wrapped versions. The wrapped versions record which zone was active when you scheduled the work, and they re-enter that zone when the callback runs. A zone is an execution context that can run hooks before and after a task.
The following table lists what Zone.js patches in a browser.
| Category | Examples |
|---|---|
| Timers | `setTimeout`, `setInterval`, `requestAnimationFrame` |
| Promises | `Promise.then`, `catch`, `finally`, `queueMicrotask` |
| DOM events | `addEventListener` on elements, `window`, `document` |
| Network | `XMLHttpRequest`, `fetch` |
| Other | Many Web APIs, such as `WebSocket` and `MutationObserver` |
Zone.js does not patch every browser API. Some newer ones, such as ResizeObserver, are not patched in all versions, so callbacks from them may run without triggering a check. Native async/await syntax cannot be patched at all. The Angular CLI works around this by compiling async/await down to Promise-based code for applications that use Zone.js.
NgZone: Angular's own zone
Angular creates a child zone called NgZone and runs your application code inside it. NgZone exposes observable properties that report when work starts and finishes:
onMicrotaskEmptyemits when the zone has no more pending microtasks, meaning the current turn of work is finished.onStableemits after that, once the zone has settled completely.onUnstableemits when work enters the zone.isStablereports whether the zone is currently idle.
The application subscribes to onMicrotaskEmpty. Each time it emits, ApplicationRef.tick() runs, and tick() performs change detection on the component tree from the root downward.
Follow the sequence for the GreetingComponent example. You scheduled setTimeout inside NgZone. Zone.js remembers that. One second later the browser fires the timer and Zone.js runs your callback in NgZone. The callback sets name. When the callback returns and no microtasks remain, NgZone emits onMicrotaskEmpty. ApplicationRef calls tick(), Angular re-evaluates {{ name }}, sees a different value, and updates the text node.
You never wrote code to trigger this. That is the point of Zone.js: all state changes made in zone-aware asynchronous callbacks are treated as potential changes.
Observing it directly
You can watch the process by injecting NgZone. The component below logs each time the zone becomes stable, and it has a button that runs a timer.
import { Component, NgZone, inject } from '@angular/core';
@Component({
selector: 'app-zone-demo',
template: `
<p>Ticks: {{ ticks }}</p>
<button (click)="start()">Start timer</button>
`,
})
export class ZoneDemoComponent {
private zone = inject(NgZone);
ticks = 0;
constructor() {
this.zone.onStable.subscribe(() => {
console.log('NgZone is stable; change detection has run');
});
}
start() {
setInterval(() => {
this.ticks++;
}, 1000);
}
}Open the browser console and click the button. The message appears once for the click event, then once per second as each timer callback completes. The ticks value on screen increases in step with those messages.
Escaping the zone on purpose
Every patched callback leads to a change detection run. That is wasteful when the callback does not touch anything the template shows. Examples are a mousemove handler that feeds a canvas, a polling loop, or a third-party chart library that registers many listeners.
NgZone.runOutsideAngular() runs a function in the parent zone. Callbacks scheduled there do not cause onMicrotaskEmpty, so they do not cause change detection. NgZone.run() moves execution back into the Angular zone.
import { Component, NgZone, OnDestroy, inject } from '@angular/core';
@Component({
selector: 'app-poller',
template: `<p>Latest value: {{ latest }}</p>`,
})
export class PollerComponent implements OnDestroy {
private zone = inject(NgZone);
private handle: ReturnType<typeof setInterval>;
latest = 0;
constructor() {
this.zone.runOutsideAngular(() => {
this.handle = setInterval(() => {
const value = Math.round(Math.random() * 100);
// Only re-enter the zone when the template needs the value.
if (value > 90) {
this.zone.run(() => {
this.latest = value;
});
}
}, 100);
});
}
ngOnDestroy() {
clearInterval(this.handle);
}
}The interval fires ten times a second, but Angular runs change detection only when value > 90. If you removed this.zone.run and assigned this.latest directly, the field would change but the screen would not, until something else triggered a check. That situation is the root of many "my view is stale" bugs, and later chapters return to it.
What a check actually does
When tick() runs, Angular walks the component tree from the root and re-evaluates each component's template bindings. For every binding it compares the new value to the stored one using strict comparison (Object.is semantics, which behaves like === for the cases that matter here). If the values differ, Angular updates the DOM.
Two details matter for later chapters:
- A tick checks the whole tree by default, regardless of which component caused the event. A click in one small button can lead to every component being re-evaluated.
- In development mode, Angular runs a second pass after each check to verify that no binding changed during the first pass. If one did, you get
ExpressionChangedAfterItHasBeenCheckedError. The error warns about an inconsistent state. It does not occur in production builds.
Checking everything on every event is correct and simple, but it is not free. The next chapter looks at what that costs.
Triggers beyond zones
Zone.js is the oldest source of notifications, but not the only one. In recent Angular versions, the framework has a change detection scheduler that also reacts to other signals:
- Calling
markForCheck()on aChangeDetectorRef. - Updating a signal that a template reads.
- Setting an input through
ComponentRef.setInput. - Attaching or removing a view.
When the scheduler is active, these notifications are sufficient to cause a check even with no Zone.js event. This is what allows applications to run without Zone.js, which a later chapter covers. In a Zone.js-based application, both mechanisms coexist. Either one can request a tick, and Angular combines the requests.
You can also reduce the number of checks that Zone.js causes. This configuration merges multiple events in the same browser frame into a single tick:
import { ApplicationConfig, provideZoneChangeDetection } from '@angular/core';
export const appConfig: ApplicationConfig = {
providers: [
provideZoneChangeDetection({ eventCoalescing: true }),
],
};With eventCoalescing: true, if a click event bubbles through several nested listeners, Angular runs one check instead of one per listener.
Common errors and edge cases
- Third-party libraries running outside the zone. A library that registers its handlers before Angular bootstraps, or that explicitly uses
runOutsideAngular, produces callbacks that do not trigger checks. Wrap the callback body inNgZone.run(). - Unpatched APIs. If a Web API is not patched, its callbacks do not re-enter the zone. The symptom is a view that updates only after an unrelated click or timer. Wrap the callback in
NgZone.run(), or use a mechanism such as a signal ormarkForCheck()that notifies the scheduler directly. - Zone-triggered loops. A recurring timer started inside NgZone triggers a check every time it fires. A
setIntervalof 16 ms runs change detection about 60 times per second. Start such timers inrunOutsideAngular. - Long-lived pending tasks. Pending macrotasks, such as a repeating timer, keep
isStablefalse. Anything that waits for stability, including server-side rendering and some end-to-end test tools, then waits for the timer to finish. - Assuming the zone knows which component changed. It does not. Zone.js signals that something ran. It does not say which component's data changed. Narrowing the set of components that Angular checks is the job of
OnPush.
Summary of the model
Zone.js answers "when to look" by wrapping asynchronous APIs and reporting when each task finishes. NgZone turns that report into the onMicrotaskEmpty event. ApplicationRef responds to the event by calling tick(), which checks every component from the root. You can opt a piece of work out with runOutsideAngular and back in with run. The scheduler adds further notification sources that do not depend on Zone.js.
Exercise
A component starts a setInterval inside NgZone.runOutsideAngular(). The callback increments a field count that the template displays as {{ count }}. The screen stays at 0 even though the field changes, and clicking an unrelated button makes the screen jump to the current value. Explain both behaviors and give one fix.
Show answer
The interval callback runs in the parent zone, so NgZone never emits onMicrotaskEmpty for it and ApplicationRef.tick() does not run. The field changes but the template is not re-evaluated. The button click is handled inside NgZone, so it triggers a tick, and that tick re-evaluates {{ count }} and shows the current value. One fix is to wrap the increment in this.zone.run(() => { this.count++; }) so the update re-enters the Angular zone. Another is to call markForCheck() or hold the count in a signal that the template reads.
Exercise
A page has 300 components. The user clicks a button in one of them. With default change detection and Zone.js, which components does Angular check, and why?
Show answer
All 300. Zone.js reports only that a patched task (the click handler) finished, not which component's data changed. NgZone emits onMicrotaskEmpty, and ApplicationRef.tick() checks the tree from the root. This is the cost that OnPush reduces.
Exercise
Why does provideZoneChangeDetection({ eventCoalescing: true }) reduce the number of change detection runs, and does it change which components are checked?
Show answer
It merges several events that occur in the same browser frame, for example one click that bubbles through nested listeners, into a single tick instead of one tick per event. It does not change which components are checked. Each tick still checks the whole tree under default change detection.