Sub topic 13
How Change Detection Updates Bindings
Earlier chapters showed what each binding form does. This chapter covers when the screen actually changes. Angular does not watch your fields directly. It runs a process called change detection: it walks the component tree, re-evaluates each template expression, compares the result with the previous value, and writes to the DOM only where something differs.
This chapter assumes you know interpolation, property and event bindings, @Input, and signals from the earlier chapters. You should also be comfortable with JavaScript's event loop, including timers and promises.
The Core Loop: Evaluate, Compare, Update
At compile time, Angular turns every binding in a template ({{ name }}, [src], [class.active], and so on) into instructions that store the last value they produced. During a change detection pass, Angular runs each instruction again:
- It evaluates the expression against the component instance.
- It compares the new value with the stored one using
Object.is, an identity check. - If the values differ, it writes the new value to the DOM node and stores it.
There is no deep comparison. For an object or array, Angular only checks whether the reference changed, never the contents. A template that reads {{ user.name }} still updates after user.name = 'Grace', because the expression itself returns a new string. What OnPush components check is the input reference (covered below), and that is where mutation causes trouble.
Event bindings sit outside this loop. They are listeners Angular attaches once. When an event fires, the handler runs, and that usually causes a change detection pass to be scheduled.
What Triggers a Pass
Angular has to know that something may have changed. There are two ways it finds out.
Zone-based detection
Historically, Angular apps loaded Zone.js. Zone.js patches browser async APIs such as addEventListener, setTimeout, Promise.then, and XMLHttpRequest. When any patched callback finishes, Angular runs a pass from the root. This is why changing a plain field inside a setTimeout simply works: Angular does not know which field changed, so it checks everything.
The cost is that every async callback triggers a pass, including ones that changed nothing, such as a third-party library's scroll listener.
Zoneless detection
Recent Angular versions can run without Zone.js, and new projects created with current CLI versions are zoneless by default. In zoneless mode, Angular schedules a pass only when it receives an explicit notification:
- A template event listener fires, for example
(click). - A signal read by a template changes.
- An input of a component changes when it is set through the template or with
ComponentRef.setInput. ChangeDetectorRef.markForCheck()is called. Theasyncpipe calls it for you.- A view is attached or removed.
Changing a plain field inside setTimeout or a fetch callback is not a notification. The screen stays stale until something else triggers a pass.
// main.ts
import { bootstrapApplication } from '@angular/platform-browser';
import { provideZonelessChangeDetection } from '@angular/core';
import { ClockComponent } from './clock.component';
bootstrapApplication(ClockComponent, {
providers: [provideZonelessChangeDetection()],
});// clock.component.ts
import { ChangeDetectionStrategy, Component, OnDestroy, signal } from '@angular/core';
@Component({
selector: 'app-root',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `<p>Seconds: {{ seconds() }}</p>`,
})
export class ClockComponent implements OnDestroy {
seconds = signal(0);
private timerId = setInterval(() => this.seconds.update(s => s + 1), 1000);
ngOnDestroy() {
clearInterval(this.timerId);
}
}The timer callback itself tells Angular nothing. The signal write does. The template read seconds(), which registered the template as a consumer of that signal. When the signal changes, Angular marks this component for a refresh and schedules a pass. If seconds were a plain number field, this component would show 0 forever without Zone.js.
Which Components Get Checked: Default vs OnPush
Triggering a pass is one question. Which components Angular visits during the pass is a separate one, and each component's change detection strategy answers it.
Default strategy
A component with ChangeDetectionStrategy.Default is checked on every pass that reaches it. This is simple and forgiving, but in a large tree every binding is evaluated on every pass.
OnPush strategy
An OnPush component is checked only if it has been marked dirty. When Angular marks a component dirty, it also marks all its ancestors, so the walk from the root can reach it. If an OnPush component is not dirty, Angular skips it and its whole subtree.
| Event | Marks the OnPush component for check? |
|---|---|
| A bound input receives a new reference (`Object.is` differs) | Yes |
| A template event listener in the component or one of its descendants fires | Yes |
| A signal read in its template changes | Yes, refreshes this view |
| The `async` pipe receives a new value | Yes, through `markForCheck` |
| `ChangeDetectorRef.markForCheck()` is called | Yes |
| A field is changed in `setTimeout` or a subscription without any of the above | No |
| An input array or object is mutated in place | No |
The last row is the most common OnPush bug:
import { ChangeDetectionStrategy, Component, Input } from '@angular/core';
@Component({
selector: 'app-tag-list',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `<p>{{ tags.length }} tags: {{ tags.join(', ') }}</p>`,
})
export class TagListComponent {
@Input() tags: string[] = [];
}
@Component({
selector: 'app-root',
imports: [TagListComponent],
template: `
<app-tag-list [tags]="tags" />
<button (click)="mutate()">Push (mutate)</button>
<button (click)="replace()">Add (new array)</button>
`,
})
export class AppComponent {
tags = ['angular'];
mutate() {
this.tags.push('mutated');
}
replace() {
this.tags = [...this.tags, 'replaced'];
}
}Clicking "Push (mutate)" runs the handler in AppComponent, so AppComponent is checked. Its [tags] binding then returns the same array reference, so the child's input is not considered changed. TagListComponent is skipped and still shows "1 tags". Clicking "Add (new array)" creates a new reference, so the child is checked and shows both new entries, including the one pushed earlier.
The fix is to treat input data as immutable, or to hold it in a signal and replace it with set or update:
tags = signal(['angular']);
add(tag: string) {
this.tags.update(list => [...list, tag]);
}Signals Make Updates Targeted
With Zone.js and the Default strategy, Angular knows that "something happened" and checks the whole tree. With signals, Angular knows that a specific template depends on a specific signal. When a signal changes, Angular marks only the views that read it. Ancestors are flagged so the traversal can reach those views, but their own bindings are not re-evaluated unless they are dirty too.
This is also why the parentheses matter. {{ count }} in a template binds to the signal function object, which never changes, so the screen shows the function's text and never updates. {{ count() }} reads the value and registers the dependency.
computed signals fit this model. A computed signal recalculates lazily, only when one of its sources changes and something reads it. Its own equality check stops a pass from going further when the derived value is unchanged.
The Development-Mode Double Check
In development mode, Angular runs a second, verification-only pass after each normal pass. It evaluates every binding again and throws NG0100: ExpressionChangedAfterItHasBeenCheckedError if any value differs. The rule being enforced is unidirectional data flow: a pass must not change state that has already been rendered.
Two typical causes:
- A template expression that returns a new value every time it runs:
import { Component } from '@angular/core';
@Component({
selector: 'app-lucky',
template: `<p>Lucky number: {{ roll() }}</p>`,
})
export class LuckyComponent {
roll() {
return Math.floor(Math.random() * 100); // different on every evaluation
}
}- A child that changes parent state during its own lifecycle hook, such as
ngAfterViewInitsetting a field the parent has already rendered.
Production builds skip the second pass, so the error disappears there, but the screen may still show stale values. Fix the cause rather than hiding it. Compute the value once in an event handler or in a computed signal, or move the state change to a point before the parent renders.
Keeping Template Expressions Cheap
Every binding in a checked component is evaluated on every pass that visits it. A method call such as {{ total() }} on a plain method (not a signal) runs its whole body each time. A few guidelines follow from this:
- Template expressions should have no side effects and return quickly.
- Move expensive derived values into
computedsignals or pure pipes. Both cache their result until their inputs change. - Prefer OnPush so that whole subtrees can be skipped.
- With
@for, provide a meaningfultrackexpression so Angular can reuse DOM nodes instead of recreating them when the array reference changes.
Manual Control with ChangeDetectorRef
Sometimes you update a plain field from code that Angular does not know about, such as a WebSocket callback or a third-party widget. Inject ChangeDetectorRef and call markForCheck():
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, OnDestroy, inject } from '@angular/core';
@Component({
selector: 'app-ticker',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `<p>Price: {{ price }}</p>`,
})
export class TickerComponent implements OnDestroy {
price = 100;
private cdr = inject(ChangeDetectorRef);
private timerId = setInterval(() => {
this.price = Math.round(this.price + (Math.random() - 0.5) * 10);
this.cdr.markForCheck();
}, 2000);
ngOnDestroy() {
clearInterval(this.timerId);
}
}markForCheck() marks the view and its ancestors dirty and, in zoneless mode, schedules a pass. detectChanges() checks this view and its children synchronously, immediately. Use it rarely, for example in tests or right after attaching a view. In most new code, converting the field to a signal removes the need for either call.
Exercise
An app uses Zone.js. An OnPush child receives [items]="items" from a Default-strategy parent. Inside a setTimeout, the parent runs this.items.push(x). Does the child update? What changes if the parent instead runs this.items = [...this.items, x]?
Show answer
With push, the child does not update. Zone.js triggers a pass and the parent is checked, but the input reference is unchanged, so the OnPush child is not marked and is skipped. With the spread, the input receives a new reference, the child is marked for check, and it renders the new list.
Exercise
A zoneless app has a component whose template shows {{ status }}, where status is a plain string field set inside a fetch(...).then(...) callback. The text never changes. Give two fixes.
Show answer
Make status a signal (status = signal('')), call status.set(...) in the callback, and read {{ status() }} in the template. Or keep the field, inject ChangeDetectorRef, and call markForCheck() after the assignment. Either one notifies Angular that a pass is needed.
Exercise
In development mode, a template contains {{ formatDate(new Date()) }}, written as a method call that receives the current time, and it sometimes throws NG0100. Explain why, and suggest a fix.
Show answer
The verification pass evaluates the expression again a moment later, and the formatted time can differ from the first pass, for example when it shows seconds. Angular reports this as a change made after the value was checked. Store the time in a field or signal, update it from a timer or event, and bind to that stable value.