Sub topic 18
How Change Detection Updates Templates, and OnPush
This chapter assumes you have read the earlier chapters on signals in templates, inputs and outputs, and lifecycle hooks. You should also be comfortable with standalone components and the imports array.
How Change Detection Works
Change detection is the process Angular uses to keep the DOM in sync with your component state. During a pass, Angular walks the component tree from the root. For each component it checks, it re-evaluates the template's bindings and updates any DOM nodes whose values changed.
Something has to schedule each pass. In apps that use zone.js, a pass runs after any browser event, timer, or HTTP response. In zoneless apps, which are the default for new projects in recent Angular versions, a pass runs when a signal read by a template changes, when a template event handler runs, or when you call markForCheck().
The Default Strategy and OnPush
With the Default strategy, Angular checks every component on every pass. That is simple, but large trees then do work they don't need to.
With ChangeDetectionStrategy.OnPush, Angular skips a component and its subtree unless the component has been marked dirty. A component is marked dirty when one of these happens:
- An input receives a new value. Angular compares object inputs by reference (
===). - An event handler in its template runs.
- A signal read in its template changes.
- Code calls
ChangeDetectorRef.markForCheck(), or theasyncpipe emits.
Signals fit well with OnPush. When a signal read in a template changes, Angular marks that component for check without any extra code.
import { ChangeDetectionStrategy, Component, input, signal } from '@angular/core';
@Component({
selector: 'app-tags',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<p>{{ owner() }}: {{ tags().join(', ') }}</p>
<button (click)="add()">Add tag</button>
`
})
export class TagsComponent {
owner = input.required<string>();
tags = signal<string[]>(['angular']);
add() {
// New array: the signal notifies and the template updates.
this.tags.update(list => [...list, 'tag' + list.length]);
}
}Lazy-Loading Template Sections with @defer
A @defer block splits its contents into a separate JavaScript chunk and renders them only when a trigger fires. The default trigger is on idle. Other triggers include on viewport, on interaction, on hover, on timer(2s), on immediate, and when condition.
import { Component } from '@angular/core';
import { TagsComponent } from './tags.component';
@Component({
selector: 'app-profile',
imports: [TagsComponent],
template: `
@defer (on viewport) {
<app-tags owner="Ada" />
} @placeholder (minimum 300ms) {
<p>Tags will appear here.</p>
} @loading (after 100ms) {
<p>Loading tags…</p>
} @error {
<p>Could not load tags.</p>
}
`
})
export class ProfileComponent {}For Angular to split the code into its own chunk, the deferred components must be standalone. They also must not be used anywhere else in the same file outside a @defer block. If either rule is broken, Angular loads the dependency eagerly with no error, and you lose the size savings. The on viewport trigger watches the @placeholder content, so the placeholder needs a single root element.
| Sub-block | Shown when |
|---|---|
| `@placeholder` | Before the trigger fires |
| `@loading` | While the chunk downloads |
| `@error` | If loading fails |
Exercise
An OnPush child receives [user]="user". The parent runs this.user.name = 'Sam' in a click handler, but the child still shows the old name. Why, and how do you fix it?
Show answer
The parent mutated the existing object, so the input reference is the same and Angular does not mark the OnPush child dirty. Assign a new object, for example this.user = { ...this.user, name: 'Sam' }, or store the user in a signal and call update so it returns a new object.
Exercise
You wrap <app-chart /> in @defer (on interaction), but the network tab shows the chart code loading with the main bundle. What is a likely cause?
Show answer
ChartComponent is referenced outside a @defer block in the same file, for example in another part of the template or in a viewChild query, or it is not standalone. Either one makes Angular load it eagerly.