Sub topic 13
Change detection and OnPush
This chapter explains how Angular decides when to re-render a template. It then switches the task list components to OnPush and shows which habits keep them correct. It assumes you finished the chapters on signals, the TaskService, and input() and output(). It also assumes you know what a standalone component and a template binding are.
What change detection does
Change detection is the process that compares the values your templates read with what is on screen. It then updates the DOM wherever they differ. Angular walks the component tree from the root downward. For each component it re-evaluates the template bindings, such as {{ task().title }} and [checked]="task().done".
In a typical app, Zone.js starts this walk. Zone.js patches browser APIs such as event listeners, setTimeout, and fetch. Whenever one of them finishes running your code, Angular runs a pass over the tree. You never call it yourself.
By default, Angular checks every component on every pass. That is simple and correct, but the cost grows with the size of the tree. A click on one checkbox re-evaluates the bindings of every task row and every other component.
The two strategies
Each component has a changeDetection setting.
Default: the component is checked on every pass.OnPush: the component is skipped unless Angular has marked it dirty.
Angular marks an OnPush component dirty in these cases:
| Trigger | Example in the task app |
|---|---|
| An input value changes by reference | The parent passes a new `Task` object to `task` |
| An event handler in the component or its template runs | The user clicks Delete in the item |
| A signal read in the template changes | `remaining()` changes after `add()` |
| A template using the `async` pipe receives a new value | An Observable emits |
| Code calls `ChangeDetectorRef.markForCheck()` | A callback sets a plain field |
Skipping applies to the whole subtree. If an OnPush component is clean, Angular does not check its children either, unless a child has its own dirty marker, such as a changed signal.
Applying OnPush to the task item
The TaskItemComponent is a good first candidate. It is presentational: everything it shows comes from the task input, and it only emits events. Add the changeDetection property.
import { ChangeDetectionStrategy, Component, input, output } from '@angular/core';
import { Task } from './task';
@Component({
selector: 'app-task-item',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<input type="checkbox" [checked]="task().done" (change)="toggled.emit(task().id)" />
<span>{{ task().title }}</span>
<button type="button" (click)="removed.emit(task().id)">Delete</button>
`,
})
export class TaskItemComponent {
readonly task = input.required<Task>();
readonly toggled = output<number>();
readonly removed = output<number>();
}Now the list component can render items through it. It also uses OnPush. It reads signals from the service, so it updates whenever tasks() or remaining() changes.
import { ChangeDetectionStrategy, Component, inject } from '@angular/core';
import { TaskItemComponent } from './task-item.component';
import { TaskService } from './task.service';
@Component({
selector: 'app-task-list',
imports: [TaskItemComponent],
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<ul>
@for (task of tasks(); track task.id) {
<li>
<app-task-item
[task]="task"
(toggled)="toggle($event)"
(removed)="remove($event)"
/>
</li>
} @empty {
<li>No tasks yet.</li>
}
</ul>
<p>{{ remaining() }} remaining</p>
`,
})
export class TaskListComponent {
private readonly service = inject(TaskService);
readonly tasks = this.service.tasks;
readonly remaining = this.service.remaining;
toggle(id: number): void {
this.service.toggle(id);
}
remove(id: number): void {
this.service.remove(id);
}
}Trace what happens when the user ticks one task:
- The
changeevent runstoggled.emit(...), and the list callsservice.toggle(id). togglereplaces the array and creates a new object only for the changed task. The other tasks keep their old object references.- The list's
tasks()signal changed, so the list is dirty and re-renders. @forusestrack task.id, so it reuses each row's component. Only the changed row receives a newtaskvalue, so only that row is dirty. The other rows are skipped.
This is why the service uses { ...t, done: !t.done } rather than t.done = !t.done. Immutable updates give OnPush a cheap, reliable test: a new reference means a change.
Why mutation breaks OnPush
Suppose some code edits a task in place.
// Wrong: the object keeps the same reference
toggleInPlace(task: Task): void {
task.done = !task.done;
}The task input still holds the same object, so Angular sees no input change. The item's OnPush view is never marked dirty, and the bindings show stale values. The bug is also inconsistent. If something else happens to dirty the component, the screen suddenly corrects itself, which makes it hard to reproduce.
Signals do not remove this rule. signal.set() and signal.update() use a reference equality check by default. If you call update(list => { list.push(x); return list; }), the array is the same reference, so the signal does not notify anyone.
Plain fields and async code
Signals are the preferred way to keep OnPush components current. A plain field changed from a callback does not mark anything dirty. Here is a small "saved" indicator that counts seconds since the last save.
import { ChangeDetectionStrategy, Component, DestroyRef, inject, signal } from '@angular/core';
@Component({
selector: 'app-saved-indicator',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `<p>Saved {{ seconds() }}s ago</p>`,
})
export class SavedIndicatorComponent {
readonly seconds = signal(0);
constructor() {
const timer = setInterval(() => this.seconds.update(n => n + 1), 1000);
inject(DestroyRef).onDestroy(() => clearInterval(timer));
}
}The setInterval callback triggers a pass because of Zone.js. If seconds were a plain number, the OnPush component would still be clean, and the text would stay at "Saved 0s ago". Making it a signal fixes this, because reading seconds() in the template registers the component as a consumer.
If you cannot use a signal, for example because a third-party library hands you a callback, inject ChangeDetectorRef and call markForCheck() after you change the field. markForCheck() marks the component and its ancestors dirty, so the next pass reaches it. It does not run a pass itself.
Common mistakes
- Mutating an input object or array. Replace it instead.
- Expecting an event in a different component to refresh an
OnPushcomponent. Events only dirty the component where the listener lives and its ancestors. - Changing plain fields in
setTimeout, subscriptions, or promises withoutmarkForCheck()or a signal. - Reaching for
ChangeDetectorRef.detectChanges()to silence a stale view. It forces a synchronous check of that view and its children, and it usually hides a mutation bug. - Applying
OnPusheverywhere without measuring. It costs little in a component that already uses signals and immutable data, but it does not make a slow app fast on its own.
Zone.js and zoneless apps
Everything above assumes Zone.js triggers passes. Recent Angular versions can run without Zone.js. A zoneless app runs a pass only when something tells Angular to: a signal read in a template changes, an event listener in a template runs, markForCheck() is called, or an async pipe receives a value. These are the same triggers OnPush already uses. Code that follows this chapter, with signals, immutable updates, and no plain fields changed in callbacks, is therefore ready to go zoneless. The opt-in is a provider in app.config.ts named provideZonelessChangeDetection(). Whether it is stable depends on your Angular version, so check the release notes before you rely on it.
Measuring
Do not guess where time goes. The Angular DevTools browser extension has a Profiler tab. It records change detection passes and shows which components were checked and how long each took. Record a pass, tick a task, and confirm that only the list and one item were checked. If every row shows up, something is dirtying them. Look for an input that receives a new reference on every pass, such as an object literal in the template ([task]="{ ...task }").
Exercise
A teammate changes TaskService.toggle to list.map(t => { if (t.id === id) t.done = !t.done; return t; }) inside update(). The list component still re-renders, because the array from map is a new reference. Why can the checkbox rows still show stale data when TaskItemComponent is OnPush?
Show answer
The array is new, so the list component re-renders and @for runs. But each task object keeps the same reference, so the task input of the changed row holds an unchanged value. The OnPush row is not marked dirty, and its bindings are not re-evaluated. The fix is to return a new object for the changed task: { ...t, done: !t.done }.
Exercise
An OnPush component has a plain field message = ''. A fetch callback sets this.message = 'Loaded'. The template shows {{ message }}, but it never updates. Give two ways to fix it.
Show answer
Make message a signal and update it with set('Loaded'), because reading the signal in the template marks the component dirty when it changes. Or inject ChangeDetectorRef and call markForCheck() after assigning the field, so the next pass checks the component.