Sub topic 2
A refresher on change detection
This chapter covers how Angular decides when and what to re-render. It assumes you can build standalone components with templates, you know basic TypeScript and async code (Promises, setTimeout, events), and you have used signal and computed. Later chapters build on this model, so we state it precisely here.
What change detection does
Change detection is the process that keeps the DOM in sync with your component state. Angular compiles each template into instructions. During change detection, Angular runs those instructions for each component, compares the new value of every binding with the value it stored last time, and updates the DOM only where a value differs.
Two questions define the whole system:
- When does Angular run change detection? This is the scheduling question.
- Which components does it check during a run? This is the traversal question.
Zone.js mostly answers the first question in a zone-based app. Zoneless mode changes the answer to the first question and leaves the second one alone. Keeping the two questions apart makes the rest of this tutorial easier to follow.
The view tree
Every component has a view. Views form a tree that mirrors your component tree, with the root component at the top. Angular walks this tree from the top down in a single pass. For each view it does the following:
- It updates the component's input bindings on its children.
- It runs lifecycle hooks such as
ngOnInit(once) andngDoCheck. - It evaluates the template bindings and writes changed values to the DOM.
- It descends into child views.
The walk is one-directional. Data flows from parents to children during the pass. This is why Angular, in development mode, runs a second "checkNoChanges" pass afterward. If a binding changed between the first and second evaluation, Angular throws ExpressionChangedAfterItHasBeenCheckedError. That error means a child or a hook modified state that a parent had already rendered.
Scheduling: when a pass runs
Angular does not poll. Something has to tell it that a pass may be needed. Most of the work in this tutorial is about identifying that "something".
In a zone-based app, Zone.js patches browser APIs such as addEventListener, setTimeout, Promise and XMLHttpRequest. When one of those callbacks finishes, NgZone signals that the zone has become stable and Angular runs ApplicationRef.tick(). In effect, any async callback you start inside the Angular zone causes a full pass. You never have to say "this changed". Angular assumes it might have.
That assumption is convenient and costly. A mousemove handler that changes nothing still triggers a pass, and the pass checks every component that is not skipped (see the next section).
In a zoneless app, nothing patches those APIs. Angular instead listens for a defined set of notifications, and later chapters cover them in detail. For now, remember the contrast: zones schedule passes implicitly after any async work, and zoneless schedules them only when something explicitly reports a change.
Traversal: which components get checked
The default strategy, ChangeDetectionStrategy.Default, checks a component on every pass. The alternative, ChangeDetectionStrategy.OnPush, lets Angular skip a component's view unless one of these is true:
- An input binding received a new value, compared by reference (
Object.is). - An event handler in the component's template, or on one of its host listeners, ran.
- A signal read in the component's template changed.
- You called
markForCheck()on itsChangeDetectorRef, or theasyncpipe did so on your behalf. - The component is marked dirty for another reason, such as being created or attached.
When one of these happens, Angular marks the component dirty and also marks every ancestor up to the root. Ancestors must be marked because the top-down walk has to reach the dirty view. The ancestors' own bindings are not necessarily re-evaluated, but the walk passes through them.
The next chapters treat OnPush as the foundation of zoneless, so the key point is worth stating now. With OnPush, a component is checked only when it has a reason to be.
A reference-comparison gotcha
Because inputs are compared by reference, mutating an object in place does not mark an OnPush child dirty.
import { ChangeDetectionStrategy, Component, input } from '@angular/core';
interface User {
name: string;
}
@Component({
selector: 'app-user-card',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `<p>{{ user().name }}</p>`,
})
export class UserCard {
readonly user = input.required<User>();
}If a parent holds const u = { name: 'Ada' } and later runs u.name = 'Grace', the reference passed to UserCard is unchanged. The child is not marked dirty and keeps showing "Ada". Replacing the object with { ...u, name: 'Grace' } produces a new reference and works. Immutable updates, or signals holding the state, avoid this problem.
Default versus OnPush in practice
| Aspect | Default | OnPush |
|---|---|---|
| Checked on every pass | Yes | Only when dirty |
| Input mutation visible | Yes | No, new reference needed |
| Works with mutable state | Yes | Needs explicit notification |
| Cost per pass | Whole tree | Only dirty branches |
Default is forgiving because it re-checks everything. The price is that every pass costs the whole tree. OnPush is cheaper, but you must make state changes visible to Angular.
How signals fit in
Signals add a third path to a dirty view. When a template reads a signal, Angular records that dependency in a reactive context for that view. When the signal's value changes, Angular marks that specific view for refresh and schedules a pass. This works whether or not the component uses OnPush, and it does not depend on Zone.js.
import { ChangeDetectionStrategy, Component, computed, signal } from '@angular/core';
@Component({
selector: 'app-cart',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<button (click)="add()">Add</button>
<p>{{ count() }} items, total {{ total() }}</p>
`,
})
export class Cart {
protected readonly count = signal(0);
protected readonly total = computed(() => this.count() * 5);
add() {
this.count.update((n) => n + 1);
}
}Here the click handler is itself a notification, since template event listeners mark the view dirty. The update to count is another notification, because the template reads count() and total(). Either one is enough to get the view refreshed.
Common errors and what they teach
- A view does not update after a
setTimeoutor a subscription callback. In anOnPushcomponent the callback changed a plain field, and nothing marked the view dirty. In a zone-based app the pass still runs, butOnPushskips the component. Fix it with a signal ormarkForCheck(). ExpressionChangedAfterItHasBeenCheckedError. A child, a pipe, or a hook changed state that a parent already rendered in the same pass. Move the change earlier, or hold the state in a signal that the parent reads after the change.- A deep object edit has no effect. This is the reference gotcha above.
- Performance drops as the app grows. Under
Defaultwith zones, every event triggers a whole-tree pass. This is the cost that motivates the next chapters.
Calling the machinery by hand
You will occasionally see these APIs. Know what each does:
ApplicationRef.tick()runs a full pass from the root now.ChangeDetectorRef.detectChanges()checks this view and its children now, synchronously.ChangeDetectorRef.markForCheck()marks this view and its ancestors dirty. It does not run a pass by itself. It relies on something else to schedule one.
The last point matters most. In a zone-based app, something almost always schedules a pass soon after, so markForCheck() appears to work on its own. In a zoneless app, Angular treats markForCheck() as a scheduling notification too, which is one reason it stays useful. A later chapter covers that behavior.
Summary of the model
- A pass walks the view tree from the root, comparing bindings and updating the DOM where values differ.
- Scheduling decides when a pass runs. Zones schedule after any async callback. Zoneless schedules on explicit notifications.
- Traversal decides which views are checked.
Defaultchecks all of them.OnPushchecks dirty ones. - Dirty marking comes from input changes, template events, signal reads,
markForCheck()and theasyncpipe. - The dev-mode second pass catches state that changes during a pass.
Exercise
A parent component with default change detection holds const settings = { theme: 'light' } and passes it as an input to an OnPush child that renders {{ settings().theme }}. A button handler in the parent runs settings.theme = 'dark'. Does the child's text update? Explain, and give two ways to fix it.
Show answer
No. The input reference is the same object, so the OnPush child is not marked dirty and is skipped. Fix 1: replace the object with a new reference, for example this.settings = { ...this.settings, theme: 'dark' }. Fix 2: hold the state in a signal, for example settings = signal({ theme: 'light' }), update it with settings.update(s => ({ ...s, theme: 'dark' })), and have the child read the signal so the read marks its view dirty.
Exercise
Separate the scheduling question from the traversal question. For each of these, say which question it answers: (a) Zone.js reporting that a setTimeout callback finished, (b) ChangeDetectionStrategy.OnPush, (c) a signal changing that is read in a template.
Show answer
(a) Scheduling, because it causes a pass to run. (b) Traversal, because it controls which views a pass checks. (c) Both: it schedules a pass and marks the reading view dirty so that the traversal includes it.