Sub topic 19
How Change Detection Updates Templates, and OnPush
This chapter assumes you already know how to read signals in templates, pass data through input() and output(), and use lifecycle hooks such as ngOnInit. It explains how Angular decides when to re-evaluate template bindings, what the OnPush strategy changes, and why signals make most change detection problems go away.
The Working Model
Change detection is the process Angular uses to keep the DOM in sync with your component state. During a pass, Angular walks the component tree from the root down. For each component it visits, it evaluates every template expression, such as {{ count() }} or [checked]="done()", and compares each result with the previous value. When a value differs, Angular updates only that DOM node.
Two separate questions decide what happens:
- When does a pass start? Something has to schedule it.
- Which components does the pass check? Each component's change detection strategy decides this.
What schedules a pass
Applications that use zone.js patch browser APIs such as setTimeout, fetch, and DOM event listeners. After any patched callback finishes, Angular runs a pass over the whole tree.
Zoneless applications don't load zone.js. You enable zoneless mode with provideZonelessChangeDetection(), and recent Angular versions use it by default for new projects. In zoneless mode, Angular schedules a pass only when it is told something changed. These notifications schedule a pass:
- A signal read by a template is set or updated.
- A template event listener fires, for example
(click). markForCheck()is called. Theasyncpipe calls it for you when its observable emits.- A component is attached to or removed from the view.
In zoneless mode, assigning a plain class field inside a setTimeout notifies nothing, so the screen does not update.
Default vs OnPush
| Strategy | When Angular checks the component during a pass |
|---|---|
| `Default` | Every pass, always |
| `OnPush` | Only when the component is marked dirty |
An OnPush component gets marked dirty when one of these happens:
- An input receives a new value. Angular compares inputs with
===, so it compares object references, not contents. - An event listener in its template, or in a child's template, fires.
- A signal read by its template changes.
markForCheck()is called on itsChangeDetectorRef, or theasyncpipe calls it.
If none of these happen, Angular skips the OnPush component and its whole subtree. That skip is where the performance gain comes from.
OnPush and Signals Together
The example below shows how OnPush treats a plain field differently from a signal.
import { ChangeDetectionStrategy, Component, OnDestroy, signal } from '@angular/core';
@Component({
selector: 'app-clock',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<p>Plain field: {{ plainSeconds }}</p>
<p>Signal: {{ signalSeconds() }}</p>
`
})
export class ClockComponent implements OnDestroy {
plainSeconds = 0;
signalSeconds = signal(0);
private timer = setInterval(() => {
this.plainSeconds++; // no notification: OnPush skips this view
this.signalSeconds.update(s => s + 1); // marks this view for refresh
}, 1000);
ngOnDestroy() {
clearInterval(this.timer);
}
}Both lines update on screen, because the signal update causes Angular to refresh the view. During that refresh, Angular also reads plainSeconds. If you remove the signal line, the plain field stops updating. That happens in a zone.js app too, because zone.js starts the pass but OnPush skips the clean component.
Local refresh with signals
When a signal read in a template changes, Angular refreshes only the view that read it. Ancestor OnPush components are traversed so Angular can reach that view, but their own bindings are not re-evaluated. Before signals, markForCheck() marked every ancestor up to the root as dirty, and all of them were re-checked. Signal-based state therefore gives you more precise updates than manual marking.
Common Errors
Mutating an input in place
import { ChangeDetectionStrategy, Component, input, signal } from '@angular/core';
@Component({
selector: 'app-tag-list',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `<p>{{ tags().join(', ') }}</p>`
})
export class TagListComponent {
tags = input.required<string[]>();
}
@Component({
selector: 'app-root',
imports: [TagListComponent],
template: `
<app-tag-list [tags]="tags" />
<button (click)="addWrong()">Add (mutate)</button>
<button (click)="addRight()">Add (new array)</button>
`
})
export class AppComponent {
tags = ['angular'];
addWrong() {
this.tags.push('wrong'); // same reference: child is not marked dirty
}
addRight() {
this.tags = [...this.tags, 'right']; // new reference: child refreshes
}
}After addWrong(), the child keeps showing the old list. The click marks AppComponent and its ancestors dirty, but not the child. The child's input still holds the same array reference, so the === check finds no change. The next time addRight() runs, the new reference refreshes the child, and both added tags appear at once. The fix is to treat state as immutable. Holding the list in a signal with update(list => [...list, x]) enforces that habit.
Changing a binding during a check
ExpressionChangedAfterItHasBeenCheckedError appears in development mode. In development, Angular runs a second verification pass right after each pass and throws if any binding produced a different value. A typical cause is setting a parent's state from a child's ngAfterViewInit. Move that logic into a computed(), or restructure your code so data flows downward.
Async results that never show
Suppose you use OnPush and write a subscription or promise result to a plain field. Angular gets no notification, so the view stays stale. Store the result in a signal instead. You can also use toSignal() for observables, or use the async pipe in the template.
Decision Criteria
| Situation | Recommendation |
|---|---|
| New component, state held in signals | `OnPush`. It costs almost nothing extra and skips work. |
| Legacy component that mutates plain fields from timers or subscriptions | Keep `Default` until you move its state to signals. |
| Large lists or dashboards | `OnPush` plus immutable updates and `track` in `@for`. |
| Zoneless application | Signals or `markForCheck()` are required anyway, so `OnPush` adds no new rules. |
ChangeDetectorRef.detectChanges() runs a pass for one component synchronously. It is useful in tests and in rare integration code with third-party libraries. In application logic, reaching for it usually means a signal is missing.
Exercise
An OnPush component receives user as an input. The parent runs this.user.name = 'Ana' inside a click handler. The child template shows {{ user().name }}. Does the child update, and how would you fix it?
Show answer
No. The click marks the parent and its ancestors dirty, not the child. The child's input still holds the same object reference, so the === comparison sees no change and Angular skips the child. Fix it by passing a new object: this.user = { ...this.user, name: 'Ana' }. Better still, store user in a signal and call this.user.update(u => ({ ...u, name: 'Ana' })).
Exercise
In a zoneless app, a Default-strategy component sets this.status = 'loaded' (a plain field) inside a fetch().then() callback. Why does the screen not change, and what is the simplest fix?
Show answer
Zoneless Angular schedules a pass only after a notification, such as a signal write, a template event, or markForCheck(). Assigning a plain field inside a promise callback sends no notification. The Default strategy only controls which components a pass checks, so it can't help when no pass runs. Make status a signal and call this.status.set('loaded').