Sub topic 2
The Default strategy and its cost
Assume you know Angular components, templates, inputs, outputs, and basic asynchronous callbacks. Angular change detection is the process that checks component state and updates the DOM when template values differ.
The Default strategy and its cost
The Default strategy checks a component whenever Angular runs a change-detection cycle. In the usual setup, Zone.js notices events, timers, promises, and other asynchronous work, then asks Angular to run a cycle.
Angular starts at the root component and walks down the component tree. With the Default strategy, it checks every attached view during that walk, even when most values have not changed.
This is simple and predictable. Its cost grows with the number of views and bindings. Frequent events, such as mouse movement, can therefore cause more work than the application needs.
OnPush: skipping subtrees that cannot have changed
OnPush tells Angular that a component can usually be skipped. Angular checks it when one of these conditions occurs:
- An input receives a new reference.
- An event handled in the component's view fires.
- The component is marked for checking.
- A signal read by its template changes.
import { ChangeDetectionStrategy, Component, input } from '@angular/core';
@Component({
selector: 'app-user-card',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `<p>{{ user().name }}</p>`,
})
export class UserCard {
user = input.required<{ name: string }>();
}Immutable updates and input reference checks
Angular compares input references. Mutating an existing object keeps the same reference, so an OnPush child might not be checked. Replace the object instead.
user = { name: 'Ada' };
replaceUser() {
this.user = { ...this.user, name: 'Grace' };
}The spread syntax creates a new object. This makes the input reference change and gives Angular a reason to check the child.
Controlling checks with ChangeDetectorRef
Use ChangeDetectorRef.markForCheck() when state changes in code Angular does not automatically associate with the view, such as a timer callback.
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, inject } from '@angular/core';
@Component({
selector: 'app-ticker',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `<p>Seconds: {{ count }}</p>`,
})
export class Ticker {
private readonly cdr = inject(ChangeDetectorRef);
count = 0;
constructor() {
setInterval(() => {
this.count++;
this.cdr.markForCheck();
}, 1000);
}
}markForCheck() schedules the view for a future Angular cycle. detectChanges() runs a check immediately, so use it only when you need that precise timing.
Exercise
Why might changing user.name fail to update an OnPush child, and what update fixes it?
Show answer
The object reference stayed the same. Replace it with { ...user, name: newName }, or mark the component for checking when the change occurs elsewhere.