Sub topic 6
OnPush: skipping subtrees that cannot have changed
This chapter assumes you know Angular components, templates, inputs and outputs, and how the Default strategy checks every component on each cycle. It covers how OnPush decides whether to check a component, what marks one dirty, and the mistakes that leave a view stale.
What OnPush changes
With the Default strategy, every component in the tree is checked on every change detection cycle. The cost grows with the number of components and bindings, even when nothing changed.
OnPush is a per-component setting. It tells Angular: "check this component only when something suggests its view may be out of date." If nothing does, Angular skips the component and all of its descendants.
import { ChangeDetectionStrategy, Component, input } from '@angular/core';
@Component({
selector: 'app-user-card',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `<p>{{ user().name }}</p>`,
})
export class UserCard {
user = input.required<{ name: string }>();
}The skipping applies to the whole subtree. If UserCard is skipped, its children are not visited either, even if they use the Default strategy. This is why OnPush pays off most near the top of large subtrees.
What makes an OnPush component get checked
An OnPush component is checked when one of these happens:
- An input binding receives a new value. Angular compares the old and new values with
Object.is, which is reference equality for objects. - An event handler in the component's own template runs, or in one of its descendants' templates. Angular marks the component and its ancestors dirty.
- The component is marked dirty explicitly, for example with
ChangeDetectorRef.markForCheck(). - A signal read in the component's template changes.
- The async pipe in its template receives a new emission. The pipe calls
markForCheck()for you.
A component that is checked in this way is checked once. After the check, it is clean again and is skipped on later cycles until another of these conditions occurs.
The flow looks like this:
Input changes are reference checks
The most common source of stale views is mutation. Angular compares an input's previous and current value by reference, not by content. If you change a property on the same object, the reference is identical, so the OnPush child sees no new input.
import { Component } from '@angular/core';
import { UserCard } from './user-card';
@Component({
selector: 'app-parent',
imports: [UserCard],
template: `
<app-user-card [user]="user" />
<button (click)="mutate()">Mutate</button>
<button (click)="replace()">Replace</button>
`,
})
export class Parent {
user = { name: 'Ada' };
mutate() {
this.user.name = 'Grace'; // same reference: the OnPush child is not updated
}
replace() {
this.user = { ...this.user, name: 'Grace' }; // new reference: the child is checked
}
}Clicking Mutate changes the data, but UserCard still shows "Ada". Clicking Replace creates a new object, so the binding [user]="user" produces a different reference and UserCard is checked.
This pushes you toward immutable updates: instead of editing an object or array in place, create a new one.
| Instead of | Use |
|---|---|
| `items.push(x)` | `items = [...items, x]` |
| `obj.count++` | `obj = { ...obj, count: obj.count + 1 }` |
| `items.splice(i, 1)` | `items = items.filter((_, j) => j !== i)` |
| `items.sort()` | `items = [...items].sort()` |
Immutable updates cost an allocation per change. For typical UI data this is cheap compared with checking thousands of bindings.
Why the parent's mutation is still visible in a second place
There is a subtlety. In the example above, the parent is a Default component, so it is checked on every cycle. Its own template bindings update normally. If the parent displayed {{ user.name }} directly, it would show "Grace" after Mutate. Only the OnPush child is stale. This is a common source of confusion: the data changed, and some views show it while others do not.
Events inside the component
An event listener in an OnPush component's template marks that component and all its ancestors dirty before the handler runs. So a button inside the component updates the view even though no input changed.
import { ChangeDetectionStrategy, Component, signal } from '@angular/core';
@Component({
selector: 'app-counter',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `<button (click)="increment()">Clicked {{ count() }} times</button>`,
})
export class Counter {
count = signal(0);
increment() {
this.count.update((c) => c + 1);
}
}Here two mechanisms apply: the template event and the signal. Either would be enough to refresh the view for this click.
Events not declared in the template do not mark the component dirty. This includes window.addEventListener, document.addEventListener, and listeners added through Renderer2 on elements outside the template's own bindings. Zone.js still triggers a cycle after such a handler runs, but an OnPush component that is not dirty is skipped during that cycle.
Timers, promises and other asynchronous work
Callbacks from setTimeout, setInterval, promises and HTTP requests start a change detection cycle when Zone.js is in use. They do not mark an OnPush component dirty. The cycle runs, reaches your component, finds it clean, and skips it.
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, inject } from '@angular/core';
@Component({
selector: 'app-ticker',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `<p>Seconds: {{ count }}</p>`,
})
export class Ticker {
private cdr = inject(ChangeDetectorRef);
count = 0;
constructor() {
setInterval(() => {
this.count++;
this.cdr.markForCheck();
}, 1000);
}
}markForCheck() marks this component and every ancestor up to the root as dirty. The ancestors must be marked because Angular walks from the root downward. If an ancestor OnPush component were skipped, Angular would never reach your component. markForCheck() does not run a check by itself. It only guarantees that the next cycle reaches and checks the component.
The example never clears its interval. In real code, store the id and call clearInterval in ngOnDestroy, or use DestroyRef.
Signals and OnPush
When a template reads a signal, Angular records that the component's view depends on it. Setting the signal to a new value marks the view for refresh, even under OnPush. You do not need markForCheck().
This works for any signal that is read in the template, including input() signals, computed signals, and signals held in services. A service that exposes readonly total = computed(...) can drive an OnPush component directly.
Two details are worth knowing:
- Setting a signal to a value equal to the current one (by default,
Object.is) does not notify consumers, so no check is scheduled. - Only reads that happen while the template runs are tracked. Reading a signal in a constructor or in a callback does not create a dependency for the view.
Choosing between Default and OnPush
| Situation | Suggested choice |
|---|---|
| Component renders only from inputs, signals or observables through the async pipe | `OnPush` |
| Large list items that appear many times | `OnPush` |
| Component mutates plain fields from timers or callbacks | Default, or `OnPush` plus `markForCheck()` |
| Small prototype where speed does not matter yet | Default |
Making OnPush the default for new components is a reasonable team convention. It forces data flow to be explicit, which makes components easier to reason about.
Common errors
- View does not update after a mutation. The input reference did not change. Replace the object or array, or pass a signal.
- View does not update after
setTimeoutor a subscription. Nothing marked the component dirty. Use a signal, the async pipe, ormarkForCheck(). - A child updates but its sibling does not. Only the dirty path from the root to the component is checked. Siblings that are clean are skipped.
detectChanges()called inside a hot path. It checks the component and its children immediately and synchronously. Overusing it hides design problems and can cost more than the Default strategy.
Exercises
Exercise
A Default parent passes [items]="items" to an OnPush child. The parent's click handler runs this.items.push('new'). The child's list does not change. Why, and what is the smallest fix?
Show answer
push mutates the array, so the reference passed to the child is the same, and the OnPush child sees no changed input. Replace the array instead: this.items = [...this.items, 'new']. Alternatively, pass a signal that holds the array.
Exercise
An OnPush component starts a setTimeout in its constructor that sets a plain field message = 'Done' after two seconds. The template shows {{ message }}, but it never changes. Name two ways to fix it.
Show answer
Make message a signal and call message.set('Done'), because the template reads the signal. Or inject ChangeDetectorRef and call markForCheck() after assigning the field. The timer starts a cycle through Zone.js, but only a dirty OnPush component is checked.