Sub topic 4
OnPush as the foundation for zoneless
This chapter assumes you can build standalone components and use signal and computed. You should also know the default change detection model, where Angular checks every component in the tree after each event. Here you will learn what ChangeDetectionStrategy.OnPush does, why a zoneless app depends on it, and which mistakes make an OnPush component stop updating.
What OnPush changes
By default, Angular checks every component each time change detection runs. In a zone-based app, Zone.js runs change detection after nearly every asynchronous task, so a plain field changed in a setTimeout still reaches the screen.
OnPush is a component setting that narrows this. Angular checks an OnPush component only when it is marked dirty. A dirty component is checked on the next change detection pass, and then it becomes clean again. Between passes, a clean OnPush component and its clean OnPush children are skipped.
import { ChangeDetectionStrategy, Component, input } from '@angular/core';
@Component({
selector: 'app-user-card',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `<h2>{{ name() }}</h2>`,
})
export class UserCard {
readonly name = input.required<string>();
}What marks an OnPush component dirty
Four things mark an OnPush component for checking:
- An input changes by reference. Angular compares the new value to the old one with
Object.is. A new object marks the component. A mutated object does not. - A template event listener runs. This covers
(click)and other listeners declared in the component's own template, or on one of its children, such as an output. Listeners attached withaddEventListenerin code do not count. - A signal read in the template changes. The template is a reactive context. When a signal it read changes value, Angular marks that component.
- Something calls
markForCheck(). Theasyncpipe calls it for you when its observable emits.
Everything else leaves the component clean. That includes a timer callback that changes a field, a resolved Promise, and a service that mutates shared state.
Why zoneless depends on it
Look at the list above and compare it with what zoneless mode needs. Without Zone.js, Angular no longer learns about every timer, Promise and XHR callback. It must be told that something changed. The OnPush triggers are exactly that kind of explicit notification.
Zoneless Angular schedules a change detection pass when one of these notifications happens: a signal read in a template changes, a template listener fires, markForCheck() is called, an async pipe receives a value, a component is created or destroyed, or an input is set on a dynamically created component. The details of the scheduler belong to a later chapter. For now, note the overlap with OnPush: a component that already works under OnPush has been written to rely only on these notifications, so it needs few or no changes when you remove Zone.js.
A component using the default strategy works in zoneless mode only if it happens to change state through one of these paths. If it changes a plain field in a timer, nothing tells Angular, and the view stays stale. Under zones the same code worked by accident, because Zone.js ran a pass after the timer.
Writing components as OnPush before you go zoneless therefore does two things. It exposes missed notifications while Zone.js is still there to cover for you in other places. It also lets you migrate one component at a time.
A component that depends on the zone
This component uses the default strategy and mutates a plain field. It works in a zone-based app.
import { Component } from '@angular/core';
@Component({
selector: 'app-ticker',
template: `<p>Ticks: {{ ticks }}</p>`,
})
export class Ticker {
protected ticks = 0;
constructor() {
setInterval(() => this.ticks++, 1000);
}
}Under zoneless mode the text stays at Ticks: 0. The interval fires and the field changes, but no signal, event, input or markForCheck() call tells Angular. Adding OnPush alone would not fix it either, because OnPush only skips work. It never creates notifications.
The fix is to hold the state in a signal.
import { ChangeDetectionStrategy, Component, signal } from '@angular/core';
@Component({
selector: 'app-ticker',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `<p>Ticks: {{ ticks() }}</p>`,
})
export class Ticker {
protected readonly ticks = signal(0);
constructor() {
setInterval(() => this.ticks.update((n) => n + 1), 1000);
}
}Now the template reads ticks(). When update changes the value, Angular marks the component dirty and schedules a pass. This code behaves the same with or without Zone.js.
Mutation versus new references
The reference check on inputs is the most common source of OnPush bugs. Consider a parent that holds a list.
import { ChangeDetectionStrategy, Component, input } from '@angular/core';
@Component({
selector: 'app-tag-list',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<ul>
@for (tag of tags(); track tag) {
<li>{{ tag }}</li>
}
</ul>
`,
})
export class TagList {
readonly tags = input.required<string[]>();
}If the parent runs this.tags.push('angular') on the same array it already passed in, the input reference is unchanged. TagList is not marked dirty and shows the old list. The parent should pass a new array, for example this.tags = [...this.tags, 'angular']. Better, the parent keeps the list in a signal and calls tags.update((t) => [...t, 'angular']). The child's input then changes by reference, and the child updates.
Signals use the same equality idea. A signal compares the new value with the old one using Object.is by default. Calling set with the same object after mutating it does not notify anyone.
What the OnPush skip covers
OnPush also affects the subtree. When Angular walks the tree and meets a clean OnPush component, it skips that component's template and everything below it, unless a descendant has been marked dirty. When a descendant is marked, Angular marks its ancestors up to the root so the walk can reach it. That is why a signal change in a deeply nested OnPush child still updates, even when its parents are clean.
This has one consequence worth knowing. A default-strategy component below an OnPush parent is only checked when the parent is checked, or when the child itself is marked dirty. In zoneless mode, a default-strategy child does not get special treatment: it is checked whenever any pass reaches it, and a pass starts only after a notification.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Child does not update after parent pushes to an array | Input mutated, same reference | Pass a new array or use a signal with `update` |
| Field changes in `setTimeout` but view is stale | Plain field, no notification | Use a signal, or call `markForCheck()` |
| Value set in a manual `addEventListener` callback is not shown | Listener is outside the template | Write to a signal, or use a template listener |
| Signal set to the same mutated object does not notify | `Object.is` sees no change | Set a new object |
| Works under zones, stale under zoneless | Default component relied on Zone.js passes | Convert to OnPush and signals |
Adopting OnPush before removing zones
A practical order for an existing app:
- Set OnPush on leaf components first. These are the cheapest to verify.
- Move component state that the template reads into signals.
- Replace mutation of inputs and shared objects with new references.
- Move outward through the tree until the root components are OnPush.
- Only then enable zoneless mode, as the next chapter shows.
You can make OnPush the default for new components with a schematic option in angular.json, so new code starts in the right shape:
{
"projects": {
"my-app": {
"schematics": {
"@schematics/angular:component": {
"changeDetection": "OnPush"
}
}
}
}
}Exercise
A parent component calls this.items.push(newItem) on an array it passes to an OnPush child through an input. The child shows the old list. Why does this happen, and name two ways to fix it.
Show answer
The input reference has not changed, because push mutates the same array. OnPush marks a component dirty on input changes only when Object.is reports a different value, so the child is never checked. Fix it by passing a new array, such as this.items = [...this.items, newItem], or by holding the list in a signal in the parent and calling items.update((list) => [...list, newItem]).
Exercise
Name the four things that mark an OnPush component dirty. Which one does a setTimeout callback that changes a plain field provide?
Show answer
An input changing by reference, a template event listener running, a signal read in the template changing, and a markForCheck() call (including the one made by the async pipe). A setTimeout callback that changes a plain field provides none of them, so in a zoneless app the view does not update.