Sub topic 6
Change detection: the background you need for profiling
The Angular DevTools profiler reports change detection cycles, so reading its output requires knowing what a cycle is, what starts one, and what each component does during it. This chapter covers that model. The next chapters use it to record and read profiles.
This chapter assumes you can write Angular components with templates and bindings, and that you have used the browser console. It uses standalone components and the built-in control flow syntax (@for, @if), as in recent Angular versions.
What change detection does
Change detection is the process that keeps the DOM in sync with your component state. Angular walks the component tree. For each component it re-evaluates the template bindings ({{ value }}, [prop]="expr") and compares each result with the value from the previous check. If a value differs, Angular updates that part of the DOM.
Three facts shape everything that follows:
- The walk goes from the root component down to its children, one pass per cycle.
- Evaluating a binding means running your code. If a template calls a method, that method runs each time the component is checked.
- A cycle is the unit the profiler measures. A long cycle means the checks in it did too much work, or too many components were checked.
What triggers a cycle
Angular does not poll. Something has to tell it that state may have changed.
Zone.js (the default)
By default Angular uses Zone.js, a library that patches browser async APIs such as event listeners, setTimeout, Promise, and XMLHttpRequest. Angular runs your code inside a zone called NgZone. When a task in that zone finishes and no microtasks remain, NgZone emits an event and ApplicationRef.tick() runs a change detection cycle.
Angular does not know which value changed. It knows only that some async work finished, so it checks the tree.
Typical triggers:
- A DOM event handled by a template listener, such as
(click). - A timer firing.
- A resolved promise or an observable emission delivered by an async API.
- An HTTP response arriving.
Signals and zoneless
When a template reads a signal, Angular records that dependency. If the signal later changes, Angular schedules a refresh of the views that read it. In zoneless applications, Zone.js is not the trigger. Signal changes, markForCheck(), the async pipe, and template event listeners schedule the cycle instead. Zoneless setup differs between Angular versions, so check the documentation for your version.
This tutorial's examples use the Zone.js model, which is still what most existing apps run.
The default strategy checks everything
With the default strategy (ChangeDetectionStrategy.Default), every component in the tree is checked in every cycle. Opening a dropdown in one corner of the page re-evaluates the bindings of a distant table component.
For small templates this costs little. It becomes a problem when a template does heavy work during evaluation. This component from the tutorial's example does:
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;
}
}There are 500 rows and 100,000 loop iterations per call, so each cycle performs 50 million iterations. Any event anywhere in the app, even a keystroke in an unrelated input, triggers that work. The profiler will show this as a long cycle with ReportComponent taking most of the time.
Dev mode runs a second pass
In development mode, Angular runs each cycle and then immediately checks the tree a second time. This second pass, often called checkNoChanges, re-evaluates every binding and compares it with the value from the first pass. A mismatch throws ExpressionChangedAfterItHasBeenCheckedError.
This has two consequences for profiling:
- Template expressions and methods run twice per cycle in dev mode, so any counter or log inside them shows double the production count.
- Template expressions must be stable within a cycle. A method that returns a new value on each call, such as
Math.random()or an incrementing counter, causes the error.
Angular DevTools requires development mode for other reasons (covered earlier), so you will always profile with this extra pass present. Absolute timings are higher than production. Compare profiles from the same mode before and after a change.
OnPush: skipping components that have not changed
ChangeDetectionStrategy.OnPush tells Angular that a component needs checking only in specific situations. Otherwise Angular skips the component and, unless something inside it is dirty, its subtree. A component with OnPush is checked when:
- One of its inputs changes by reference (a new value according to
===). Mutating an object you already passed in does not count. - An event listener in its template, or in one of its descendants' templates, fires.
- A signal read in its template changes.
- It is explicitly marked, through
ChangeDetectorRef.markForCheck(). Theasyncpipe calls this for you when a new value arrives.
| Situation | Default component | OnPush component |
|---|---|---|
| Unrelated event elsewhere in the app | Checked | Skipped |
| Input receives a new reference | Checked | Checked |
| Input object mutated in place | Checked | Skipped |
| Event in its own template | Checked | Checked |
| Signal it reads changes | Checked | Checked |
| `markForCheck()` called | Checked | Checked |
When an event fires, Angular marks the component that owns the listener and all of its ancestors up to the root as dirty. It does not mark siblings or descendants. That is why a click in one component does not force its OnPush siblings to be checked.
Seeing the difference
This runnable example logs each time a child's template is evaluated. The method returns a constant, so it does not trigger the dev mode error.
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
@Component({
selector: 'app-default-child',
standalone: true,
template: `<p>{{ log('default child') }}</p>`,
})
export class DefaultChildComponent {
log(label: string): string {
console.log(`${label} checked`);
return label;
}
}
@Component({
selector: 'app-onpush-child',
standalone: true,
changeDetection: ChangeDetectionStrategy.OnPush,
template: `<p>{{ log('onpush child') }}</p>`,
})
export class OnPushChildComponent {
log(label: string): string {
console.log(`${label} checked`);
return label;
}
}
@Component({
selector: 'app-root',
standalone: true,
imports: [DefaultChildComponent, OnPushChildComponent],
template: `
<button (click)="clicks = clicks + 1">Clicked {{ clicks }} times</button>
<app-default-child />
<app-onpush-child />
`,
})
export class AppComponent {
clicks = 0;
}
bootstrapApplication(AppComponent);Serve this in development mode and open the console. On load, both children log. After the first click on the button, only default child checked appears. It appears twice because of the dev mode second pass. The OnPush child is skipped because it has no inputs that changed, no events of its own, and no signals. The button belongs to the root, so only the root and the default child are checked.
The cycle as a flow
The diagram shows what happens from trigger to DOM update in the Zone.js model.
The profiler's flame graph and bar chart are built from this walk. Each bar corresponds to a cycle, and each segment inside it to a component's checks.
Common errors and gotchas
- Mutating inputs under OnPush. If a parent does
this.items.push(x)and passesitemsto an OnPush child, the reference is unchanged and the child does not update. Pass a new array (this.items = [...this.items, x]) or use signals. - Updating state outside the zone. Code running outside
NgZone(for example insidengZone.runOutsideAngular, or some third-party libraries) does not trigger a cycle. The data changes but the view does not. CallngZone.run(...)ormarkForCheck()to re-enter. - Methods in templates. Under the default strategy these run every cycle, as
expensiveTotaldid above. Moving the work into acomputedsignal or a precomputed field means it runs only when the data changes. - Trusting log counts in dev mode. Remember the double evaluation.
- Treating OnPush as a cure-all. OnPush reduces how often a component is checked. It does not make an expensive check cheaper when it does run.
What to carry into profiling
When you open the profiler, you will be asking three questions that this chapter has prepared you for:
- What triggered this cycle (the source column), and was it expected?
- Which components were checked, and could they have been skipped?
- Is the time spent in a component's own bindings, or in its children?
The first answer points to events and timers. The second points to missing OnPush or in-place mutation. The third points to expensive template expressions. The chapter after next applies exactly these questions to a recorded session.
Exercise
A parent component passes config (an object) to an OnPush child. A button handler in the parent runs this.config.theme = 'dark', which mutates the object in place. The child's template displays config().theme-style data from that input, but the screen does not change. Why, and name two ways to fix it.
Show answer
The OnPush child is checked only if an input reference changes, an event fires in its own template or its descendants, a signal it reads changes, or it is marked with markForCheck(). Mutating the object in place leaves the reference the same, and the click happened in the parent, so none of these conditions is met. Fixes: replace the object with a new one (this.config = { ...this.config, theme: 'dark' }), or hold the config in a signal and update it with set/update so the child's read of that signal schedules a refresh. Calling markForCheck() on the child's ChangeDetectorRef also works but is more manual.
Exercise
You add console.log('checked') to a method called from a default-strategy component's template, then click a button once. The console shows checked twice. Is the component being checked twice per click in production? Explain.
Show answer
No. In development mode Angular runs a second pass (checkNoChanges) after each cycle to verify that no binding value changed, so template expressions are evaluated twice. In a production build there is no second pass, and the method would run once per click.