Sub topic 9
Fixing slow change detection with OnPush
This chapter assumes you can read a profiler recording from the previous chapters. You should know that the Angular DevTools profiler shows each change detection cycle as a bar, and that a long bar means a slow cycle. You should also know basic signals and the @for block.
The problem the profile shows
Suppose you record a session while clicking around the report page. Every cycle is long, even when the click has nothing to do with the report. Selecting the ReportComponent bar shows that most of the time goes to this one component.
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;
}
}This component uses the default strategy. Angular checks it on every cycle, and each check re-evaluates expensiveTotal 500 times. That is about 50 million loop iterations per cycle.
Why OnPush helps
With ChangeDetectionStrategy.OnPush, Angular skips a component and its subtree until something marks it dirty. These events mark it dirty:
- An
@Inputreceives a new reference. - An event listener in the component's template fires.
- A signal read in the template changes.
- The
asyncpipe emits a new value. - Your code calls
markForCheck().
OnPush alone is not enough here. The method call is still slow whenever the component is checked. So the fix also moves the calculation into a computed signal, which recalculates only when its inputs change.
The fixed component
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),
}))
);
}The template now reads a cached value. The sum also uses a direct reduce over three numbers instead of the artificial 100,000-step loop. In real code, the point is that expensive work belongs in a cached value, not in a template method.
Verify with a new profile
Do not assume the change worked. Measure it.
- Reload the app in development mode and open the Profiler tab.
- Repeat the exact interaction you recorded before, then stop recording.
- Select the
ReportComponentbar and compare its time with the first recording. - Check that the component no longer appears in cycles it has no reason to join.
The Profiler's per-component breakdown also shows how much time goes to the component's own template, so you can compare like with like.
Common mistakes
| Symptom after switching to OnPush | Likely cause | Fix |
|---|---|---|
| View does not update after an HTTP response | Plain property changed with no dirty mark | Store the value in a signal, or use `async` |
| Child ignores a parent's change | Object mutated in place | Pass a new reference |
| Cycles are still long | Heavy work still runs in the template | Move it into `computed` |
Exercise
After adding OnPush to a list component, a parent adds an item with this.items.push(newItem) and the child list does not update. Why, and what is the smallest fix?
Show answer
push mutates the array without changing its reference, so the OnPush child's input looks unchanged and the component is not marked dirty. Assign a new array, for example this.items = [...this.items, newItem], or keep the items in a signal and call set or update with a new array.