Sub topic 2
What Makes an OnPush Component Get Checked
Assume you know Angular templates, component inputs, and basic RxJS Observables. OnPush narrows when Angular checks a component's template. This can reduce work in large component trees, but updates must follow clear notification rules.
What Makes an OnPush Component Get Checked
Angular checks an OnPush component when one of these events occurs:
- A bound input receives a new value. For objects and arrays, this normally means a new reference.
- An event runs in the component or one of its child components.
- An Observable used with the
asyncpipe emits. - A signal read by the template changes.
- Code calls
markForCheck()or another API marks the view. - Code calls
detectChanges()directly on the component's change detector.
The component is then included in a change-detection pass. OnPush does not mean “check only once.” It means Angular can skip the component until a relevant notification occurs.
Displaying Observables with the async Pipe
The async pipe subscribes to an Observable and displays its latest value. Each emission also marks the component for checking. Angular manages the subscription and unsubscribes when the view is destroyed.
import { AsyncPipe } from '@angular/common';
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { Observable, timer } from 'rxjs';
import { map } from 'rxjs/operators';
@Component({
selector: 'app-clock-ticks',
imports: [AsyncPipe],
changeDetection: ChangeDetectionStrategy.OnPush,
template: `<p>Seconds: {{ seconds$ | async }}</p>`,
})
export class ClockTicksComponent {
seconds$: Observable<number> = timer(0, 1000).pipe(map((n) => n));
}Manual Control with ChangeDetectorRef
Use ChangeDetectorRef when asynchronous code updates a plain field through a manual subscription. Call markForCheck() after changing the field. This schedules the component for a later change-detection pass.
this.count++;
this.cdr.markForCheck();detectChanges() runs detection immediately for the view and its descendants. Use it sparingly. Prefer the async pipe or signals when they fit the design.
Exercise
Why does an async pipe update an OnPush view without an explicit markForCheck() call?
Show answer
The pipe subscribes to the Observable and marks its view for checking whenever a new value arrives.