Sub topic 9
Fixing slow change detection with OnPush
This chapter assumes you can read a profiler recording from the previous chapters: you know how to start a recording, select a bar, and read the per-component timings. It also assumes you know Angular signals and standalone components at a basic level. You will take a slow component, find out why it is slow, apply OnPush, and confirm the result with a second profile.
Why the default strategy gets slow
With the default strategy, Angular checks every component in the tree on every change detection pass. A pass runs after any event that Zone.js reports, such as a click, a timer, or an HTTP response. For each component, Angular re-evaluates every binding in its template and compares the result with the previous value.
Checking a binding is cheap when it reads a property. It is expensive when the template calls a method that does real work. The method runs on every pass, whether or not its inputs changed. In development mode Angular also runs a second verification pass (checkNoChanges), so the method runs twice per cycle.
Here is a component with this problem:
import { Component } from '@angular/core';
@Component({
selector: 'app-report',
standalone: true,
template: `
@for (row of rows; track row.id) {
<p>{{ row.name }}: {{ expensiveTotal(row) }}</p>
}
`,
})
export class ReportComponent {
rows = Array.from({ length: 500 }, (_, i) => ({ id: i, name: `Row ${i}`, values: [i, i + 1, i + 2] }));
// Called for every row on every change detection pass.
expensiveTotal(row: { values: number[] }): number {
let total = 0;
for (let n = 0; n < 100000; n++) {
total += row.values[n % row.values.length];
}
return total;
}
}The method does 100,000 loop iterations for each of 500 rows. That is 50 million iterations per pass, and 100 million in development mode. Any unrelated event in the page, even a mouse click on a button elsewhere, triggers a pass and pays this cost.
Confirm the diagnosis in the profiler
Do not start rewriting until the profile points at the component. Use this procedure:
- Serve the app in development mode and open Angular DevTools.
- Open the Profiler tab and click Start recording.
- Perform one action that should be cheap, such as clicking a button that changes nothing in the report.
- Click Stop recording.
- Select the tallest bar. The bar's height is the total time of that change detection cycle.
- Open the flame graph or the ranked list for the selected cycle and find
ReportComponent.
Look for two things. First, the cycle should be long compared with the frame budget of about 16 ms at 60 frames per second. Second, ReportComponent should account for nearly all of that time. If a cycle is long but the time is spread across many components, the fix is different. Spread-out cost points at too many components being checked, not at one costly binding.
Also note the source shown for the cycle. DevTools reports what triggered it, for example a click listener. A cheap trigger that produces an expensive cycle is the classic case for OnPush.
Write down the numbers for the cycle: its duration and ReportComponent's share. You need them for the comparison later.
What OnPush changes
ChangeDetectionStrategy.OnPush tells Angular to skip a component and its subtree unless the component is marked dirty. A component becomes dirty in these cases:
- An input binding receives a new value. Angular compares by reference (
===), not by content. - An event handler declared in the component's template or host bindings runs.
- A signal read in the template changes value.
- An
asyncpipe in the template receives a new emission. - Code calls
ChangeDetectorRef.markForCheck().
The component is always checked once on creation. Otherwise it is skipped.
OnPush alone does not fix the example above. The method call is still in the template, so it still runs whenever the component is checked. The second half of the fix is to move the work out of the template so that it runs only when its data changes.
The fix: OnPush plus a computed signal
import { ChangeDetectionStrategy, Component, computed, signal } from '@angular/core';
@Component({
selector: 'app-report',
standalone: true,
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
@for (row of totals(); track row.id) {
<p>{{ row.name }}: {{ row.total }}</p>
}
`,
})
export class ReportComponent {
rows = signal(Array.from({ length: 500 }, (_, i) => ({ id: i, name: `Row ${i}`, values: [i, i + 1, i + 2] })));
// Recomputed only when `rows` changes.
totals = computed(() =>
this.rows().map((r) => ({
id: r.id,
name: r.name,
total: r.values.reduce((a, b) => a + b, 0),
}))
);
}Three changes matter here:
changeDetection: ChangeDetectionStrategy.OnPushlets Angular skip the component when nothing marked it dirty.computedcaches its result. It re-runs only when a signal it read, hererows, changes. Readingtotals()during later passes returns the cached array.- The template now reads a plain property,
row.total, so a pass that does check the component costs almost nothing.
This version computes a plain sum instead of the artificial 100,000-step loop, so the displayed numbers differ from the first version. The point of the comparison is where the work happens, not the arithmetic.
Using computed without OnPush already removes most of the cost. Using OnPush without moving the work out of the template removes the cost only on passes where the component is skipped. Doing both is the most robust choice, because a later input change or event will not bring the expensive work back.
Verify with a second profile
Repeat the recording with the same steps as before. Using the same action matters, since a different action makes the comparison meaningless.
| What to compare | Before | What you expect after |
|---|---|---|
| Duration of the cycle for the cheap action | Long, often well above 16 ms | Short, a few milliseconds or less |
| `ReportComponent` in the cycle | Dominates the time | Absent, or a negligible entry |
| Bars for actions that change `rows` | Same as other cycles | One longer cycle, since `totals` recomputes once |
If the component still shows up in every cycle, work through the causes below.
Common errors with OnPush
Mutating an input instead of replacing it
OnPush compares input references. If a parent pushes into an array it already passed down, the reference does not change and the child never updates.
import { ChangeDetectionStrategy, Component, input } from '@angular/core';
@Component({
selector: 'app-row-list',
standalone: true,
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
@for (row of rows(); track row.id) {
<p>{{ row.name }}</p>
}
`,
})
export class RowListComponent {
rows = input.required<{ id: number; name: string }[]>();
}
@Component({
selector: 'app-parent',
standalone: true,
imports: [RowListComponent],
template: `
<button (click)="add()">Add</button>
<app-row-list [rows]="rows" />
`,
})
export class ParentComponent {
rows = [{ id: 1, name: 'First' }];
add(): void {
// Bug: this.rows.push(...) keeps the same array reference, so the child is not updated.
this.rows = [...this.rows, { id: this.rows.length + 1, name: 'Added' }];
}
}The symptom is a UI that does not update, which is the opposite of a performance problem. Angular DevTools helps here. Select the child in the component explorer and check whether its input shows the new value. If the data is correct but the screen is stale, the component was not marked dirty.
State changed outside Angular's knowledge
A plain property assigned inside a setTimeout or a third-party callback does not mark an OnPush component dirty. Store such state in a signal, expose it through an async pipe, or call markForCheck() after the change.
A default-strategy ancestor keeps checking its own bindings
An OnPush child is skipped only when it is not dirty, but its default-strategy parent is still checked on every pass. If the profile shows a parent with a long own time, the cost is in the parent's template, and OnPush on the child will not help.
Expecting OnPush to fix expensive work
OnPush reduces how often a component is checked. It does not make the work cheaper. If a handler legitimately needs 200 ms of computation, moving it to OnPush changes nothing. In that case, reduce the amount of work with memoization, pagination, or virtual scrolling.
A short checklist
- Record a cheap action and find the long cycle.
- Identify the component that dominates the cycle.
- Look in its template for method calls, getters that do work, and impure pipes.
- Move the work into a
computedsignal or a pure pipe. - Add
OnPush, and make sure inputs are replaced rather than mutated. - Record the same action again and compare the cycle duration.
- Click through the features of the component to confirm that it still updates when it should.
Exercise
A parent component passes an array to an OnPush child with [items]="items". The parent's button handler calls this.items.push(newItem). The array contents are correct in the DevTools property view of the parent, but the child's list on screen does not change. Why, and what is the fix?
Show answer
The push mutates the array in place, so the input reference is unchanged. An OnPush component is marked dirty by input changes only when the reference differs, so the child is skipped. Replace the array instead, for example this.items = [...this.items, newItem], or hold the items in a signal and update it with a new array.
Exercise
You add changeDetection: ChangeDetectionStrategy.OnPush to the first ReportComponent and leave expensiveTotal(row) in the template. In a new profile, clicking an unrelated button in the page no longer shows ReportComponent, but clicking a button inside the report still produces a long cycle. Explain both observations.
Show answer
The unrelated click does not mark the OnPush component dirty, so Angular skips it and its template method does not run. A click on a button inside the report's own template is an event in that component, which marks it dirty. Angular then checks it and calls expensiveTotal for every row again. Moving the work into a computed signal removes the cost in both cases, because the template reads cached values.