Sub topic 2
Default change detection and its cost
This chapter assumes you can build a standalone component with template bindings and @Input, and that you know the difference between mutating an object and replacing it. It also assumes that Zone.js notifies Angular after events, timers and HTTP calls, as the previous chapter covered. Here you will see what Angular does on each of those notifications under the default strategy, why the cost grows with the size of the app, and how to measure it.
What "default" means
Every component has a change detection strategy. If you set nothing, it is ChangeDetectionStrategy.Default. Angular's internal name for this behavior is "check always", and it describes the rule well: whenever change detection runs, this component is checked.
Change detection runs as one pass over the whole component tree. Angular starts at the root component and walks down depth-first. For each component it does the following:
- Updates the component's input bindings from the parent.
- Evaluates every binding expression in its template.
- Compares each result with the value stored from the previous pass.
- Writes to the DOM only where a value differs.
A default component is not skipped because its inputs look the same or because nothing happened near it. The walk visits every component in the app, and the cost is paid again on every pass.
What happens during one check
Evaluating bindings is the main cost, but it is not the only work. Angular also calls lifecycle hooks during the walk.
| Hook | When it runs during a pass |
|---|---|
| `ngOnChanges` | Only when a bound input value changed |
| `ngDoCheck` | On every check of the component |
| `ngAfterContentChecked` | On every check, after projected content is checked |
| `ngAfterViewChecked` | On every check, after the view and child views are checked |
Any code you put in ngDoCheck or the *Checked hooks therefore runs on every pass, for every instance of the component. A hook that does real work becomes expensive quickly when the component appears in a large list.
In development mode, Angular also runs a second verification pass called checkNoChanges. It evaluates every binding again and throws NG0100: ExpressionChangedAfterItHasBeenCheckedError if any value differs from the first pass. This catches bindings that are not stable within a single pass. It also means that in development, template expressions run about twice as often as they do in production.
Where the cost comes from
The cost of one pass is roughly the number of bindings in the tree multiplied by the price of evaluating each one. The number of passes depends on how often something triggers a tick. Three factors drive the total.
- Tree size. Ten thousand bindings are visited whether or not any of them could have changed.
- Expensive expressions. A method call, getter or inline computation in a template runs on every pass. Plain property reads are cheap. A method that filters an array is not.
- Trigger frequency. Zone.js notifies Angular after any event handler, timer or promise in the zone. This includes events your template does not care about, such as a
mousemoveorscrolllistener, or asetIntervalthat updates nothing visible.
Measuring it with a counter
The following example makes the cost visible. Each row calls a formatting method from its template, and a static counter records how many times the method runs.
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-price-row',
template: `<li>{{ format() }}</li>`,
})
export class PriceRowComponent {
static calls = 0;
@Input({ required: true }) cents!: number;
format(): string {
PriceRowComponent.calls++;
return `$${(this.cents / 100).toFixed(2)}`;
}
}The parent renders 1,000 rows. It has a button that does nothing and a button that copies the counter into a field so the number can be displayed. The counter is copied inside a click handler, not read in the template. If the template read the static field directly, its value would change during the pass and trigger NG0100.
import { Component } from '@angular/core';
import { PriceRowComponent } from './price-row.component';
@Component({
selector: 'app-price-list',
imports: [PriceRowComponent],
template: `
<button (click)="noop()">Do nothing</button>
<button (click)="snapshot()">Show count</button>
<p>format() calls so far: {{ shown }}</p>
<ul>
@for (cents of prices; track $index) {
<app-price-row [cents]="cents" />
}
</ul>
`,
})
export class PriceListComponent {
prices = Array.from({ length: 1000 }, (_, i) => 100 + i);
shown = 0;
noop() {
// Intentionally empty. The click still ends with a change detection pass.
}
snapshot() {
this.shown = PriceRowComponent.calls;
}
}Run this in development mode and click "Show count". You should see a number near 2,000, which is 1,000 rows evaluated in the update pass plus 1,000 in the checkNoChanges pass. Click "Do nothing" five times and click "Show count" again. The number grows by roughly 10,000 even though no data changed. Each click ended with a full pass, and each pass called format() on every row. In a production build the growth is about half as large.
Fixing the expensive expression
Moving the work out of the method changes how often it runs. A pure pipe re-runs only when its input value changes, so a row whose cents input is unchanged skips the work. The built-in currency pipe is pure:
import { CurrencyPipe } from '@angular/common';
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-price-row',
imports: [CurrencyPipe],
template: `<li>{{ cents / 100 | currency }}</li>`,
})
export class PriceRowComponent {
@Input({ required: true }) cents!: number;
}The component is still checked on every pass. Angular still visits the binding and compares its inputs, but the formatting work no longer repeats. This is the limit of what you can do inside the default strategy: you can make each visit cheaper, but you cannot reduce the number of visits. Reducing the visits is what OnPush does, and the next chapter introduces it.
Reducing triggers without changing the strategy
Some passes are avoidable at the source. If a listener updates state that no template displays, it does not need to run inside the Angular zone. NgZone.runOutsideAngular registers the listener without notifying Angular afterwards.
import {
Component,
ElementRef,
NgZone,
OnInit,
inject,
} from '@angular/core';
@Component({
selector: 'app-pointer-tracker',
template: `<div class="pad">Move the pointer here</div>`,
})
export class PointerTrackerComponent implements OnInit {
private zone = inject(NgZone);
private host = inject<ElementRef<HTMLElement>>(ElementRef);
lastX = 0;
ngOnInit() {
this.zone.runOutsideAngular(() => {
this.host.nativeElement.addEventListener('mousemove', (event) => {
// Plain field update. No tick is scheduled by this listener.
this.lastX = event.clientX;
});
});
}
}Edge cases to know about
- Getters are method calls.
get total() { return this.items.reduce(...) }in a template runs on every pass, exactly like a method. - A pass starts at the root, not at the source of the event. Clicking a button deep in the tree checks the whole tree, including branches unrelated to the click.
- Order matters. A parent's bindings are evaluated before its children are checked. A child that changes state its parent has already rendered causes
NG0100in development mode. - Ticks can overlap with work you do not see. Third-party libraries that start timers or listeners inside the zone cause passes you did not write code for. A polling timer inside a library can tick the whole app every second.
- Development numbers overstate production. The doubled evaluation in development comes from
checkNoChanges. Measure with a production build before deciding something is too slow.
When the default is fine
The default strategy is correct and safe. It never leaves a view stale, because it checks everything on every notification. For small and medium apps, the cost is often below the point where anyone would notice, and the simplicity is worth keeping. Move to OnPush when you have evidence of a problem. Typical evidence includes visible lag during typing or scrolling, a profiler showing long change detection times, or large lists of components that rarely change.
Two tools help gather that evidence:
- Angular DevTools profiler. It records each change detection pass and shows how long each component took, so you can find the components that are checked most often or evaluate slowly.
- A lightweight
ngDoCheckcounter. Temporarily addngDoCheck() { console.count('MyComponent'); }to a suspect component to see how often it is visited. Remove it afterwards, since it adds work to every pass.
Key points
- The default strategy checks every component on every pass, from the root down, whether or not its data could have changed.
- A pass evaluates all template bindings and runs
ngDoCheckand the*Checkedhooks. - Cost scales with binding count, with the price of each expression, and with how often Zone.js triggers a pass.
- Pure pipes and precomputed values make each visit cheaper. They cannot reduce the number of visits.
- Development mode evaluates bindings twice per pass, so profile production builds.
Exercise
A template contains {{ getTotal() }}, and getTotal() loops over 5,000 items. The component uses the default strategy. A timer inside the Angular zone fires every 500 ms and changes a field that no template displays. How often does getTotal() run, and what are two ways to reduce the work without switching to OnPush?
Show answer
It runs on every change detection pass, so at least twice per second because of the timer, and twice that in development mode because of the checkNoChanges pass. The timer triggers a pass even though nothing visible changed. You can (1) replace the method with a precomputed field or a pure pipe so the loop runs only when its inputs change, and (2) start the timer inside NgZone.runOutsideAngular so it stops triggering passes, since its field is not displayed.
Exercise
In the price list example, you add a text input to the parent with (input)="query = $any($event.target).value", and query is not used in any template. Does typing in it cause the 1,000 rows to be checked? Why?
Show answer
Yes. The input event handler runs inside the Angular zone. When it finishes, Zone.js notifies Angular, which runs a full pass from the root. Under the default strategy the rows are checked, and each row's format() method runs again, even though query is never displayed. The check does not depend on what the handler changed.