Sub topic 1
How Angular learns that something may have changed
Prerequisites
Assume you can build Angular components, bind template expressions, pass inputs, and use basic RxJS Observables. You should also know that JavaScript objects are references, while copied objects have different references.
How Angular learns that something may have changed
Angular does not continuously compare every value in an application. It runs change detection, which evaluates component templates and updates the DOM when a binding has changed.
In a typical application, Zone.js observes asynchronous work such as events, timers, and completed HTTP requests. After such work finishes, Angular schedules a change-detection pass. The pass starts near the application root and visits component views.
Default change detection and its cost
The default strategy checks a component whenever Angular runs a change-detection pass. It also checks the component's descendants, even when their inputs probably did not change.
This behavior is simple and reliable. Its cost grows with the number of views and bindings. A frequent timer, user event, or network response can cause Angular to evaluate a large component tree. The DOM may not change, but Angular still performs the checks.
Opting in with `ChangeDetectionStrategy.OnPush`
OnPush narrows when Angular checks a component. Enable it in the component metadata:
import { ChangeDetectionStrategy, Component, Input } from '@angular/core';
@Component({
selector: 'app-user-card',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `<p>{{ user.name }}</p>`,
})
export class UserCardComponent {
@Input({ required: true }) user!: { name: string };
}Angular checks an OnPush component when it receives a new input reference, handles an event in that component, or is explicitly marked for checking. Signals and the async pipe can also notify Angular when their values change.
Input changes are reference checks: immutable updates
For an object input, OnPush primarily detects a changed reference. Changing a property keeps the same reference, so the child can display stale data. Create a new object instead:
// Stale for an OnPush child:
this.user.name = 'Grace';
// Detected by the child:
this.user = { ...this.user, name: 'Grace' };Exercise
Why might an OnPush child fail to display a changed name property?
Show answer
The parent mutated the existing object, so its reference did not change. Replace it with a copied object.