Sub topic 5
What makes an OnPush component get checked
This chapter assumes you can build Angular components with templates and data binding, pass data through inputs and outputs, and read basic RxJS code. It also assumes you know the difference between mutating an object and replacing it with a copy.
An OnPush component is not checked on every change detection pass. Angular skips it unless something marks it as needing a check. This chapter lists exactly what does that, what does not, and how to reason about a view that refuses to update.
The mental model: a dirty flag
Each OnPush component view has a flag that means "this view needs checking". During a change detection pass, Angular walks the component tree from the root. At an OnPush component it looks at the flag.
- If the flag is set, Angular checks the component's template bindings, runs its lifecycle hooks for that pass, clears the flag, and continues into its children.
- If the flag is not set, Angular skips the component's own template. It still visits the component's children only if they have something that needs refreshing, such as a signal read in their templates that changed.
Zone.js, or the zoneless scheduler, only tells Angular that a pass should run. The dirty flag decides which OnPush components take part in that pass. That is why a timer firing somewhere in the app can run a pass without changing the screen of a given OnPush component.
The triggers
An OnPush component is marked for checking in these situations.
- An input binding receives a new value, compared with
Object.is(strict identity, withNaNequal to itself). - A template event listener on the component or one of its descendants runs, including host listeners.
- The
asyncpipe in the component's template receives a new value. - Code calls
ChangeDetectorRef.markForCheck()for the component or a descendant. - A signal read in the template changes.
- The component is created, which gives it its first check.
Each trigger is covered below. The common thread is that Angular has to be told. It does not watch your fields.
1. A new input reference
Angular compares the previous and the current value of each input binding. For objects and arrays, the comparison is by reference, not by content. The component from the earlier chapters shows this:
import { ChangeDetectionStrategy, Component, Input } from '@angular/core';
export interface User {
name: string;
}
@Component({
selector: 'app-user-card',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `<p>{{ user.name }}</p>`,
})
export class UserCardComponent {
@Input({ required: true }) user!: User;
}A parent that changes user.name in place leaves the reference unchanged, so the input check finds nothing new and the card stays stale. A parent that assigns a new object marks the card for checking.
import { Component } from '@angular/core';
import { User, UserCardComponent } from './user-card.component';
@Component({
selector: 'app-parent',
imports: [UserCardComponent],
template: `
<app-user-card [user]="user" />
<button (click)="renameByMutation()">Mutate</button>
<button (click)="renameImmutably()">Replace</button>
`,
})
export class ParentComponent {
user: User = { name: 'Ada' };
renameByMutation() {
// Same object reference: the OnPush child does not update.
this.user.name = 'Grace';
}
renameImmutably() {
// New reference: the OnPush child is checked and shows the new name.
this.user = { ...this.user, name: 'Grace' };
}
}Primitive inputs (strings, numbers, booleans) behave as you would expect, because equal values are identical. Setting an input from 5 to 5 does nothing, and from 5 to 6 marks the component.
2. An event from the component's own template
When a listener declared in the component's template runs, Angular marks that component and all of its ancestors up to the root. The ancestors are marked so that the path from the root down to the component stays reachable during the pass.
The trigger fires when the listener is invoked, whether or not the handler changes any data. That has two consequences.
- A click inside an OnPush component refreshes that component, so a button that increments a field in the same component works without any extra code.
- An event in a child marks the parent chain too, so the parent's template is also checked on that pass.
Events that do not come from the template do not count. A setTimeout callback, a WebSocket message, or a listener you added with addEventListener is not a template event. Zone.js can still schedule a pass for them, but they do not mark your component.
Outputs are different from DOM events. When a child emits through an EventEmitter or output(), the parent's handler runs because the parent's template declared it, and that listener marks the parent. The child is not marked by its own emission.
3. The async pipe
The async pipe subscribes to an Observable or Promise from the template. Each time a value arrives, the pipe stores it and marks the component for checking. The pipe also unsubscribes when the view is destroyed.
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { AsyncPipe } from '@angular/common';
import { Observable, timer } from 'rxjs';
import { map } from 'rxjs/operators';
@Component({
selector: 'app-clock-ticks',
imports: [AsyncPipe],
changeDetection: ChangeDetectionStrategy.OnPush,
template: `<p>Seconds elapsed: {{ seconds$ | async }}</p>`,
})
export class ClockTicksComponent {
seconds$: Observable<number> = timer(0, 1000).pipe(map((n) => n));
}The pipe marks the component that contains it. It does not mark a parent or child. If the pipe is in the template of an OnPush component, only that component, and the ancestors needed to reach it, are scheduled.
4. markForCheck
When state changes outside the template, you can mark the component yourself. markForCheck() sets the dirty flag on the component and its ancestors. It does not run change detection. It only guarantees that the next pass reaches this component.
import {
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
DestroyRef,
inject,
OnInit,
} from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { interval } from 'rxjs';
@Component({
selector: 'app-counter',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `<p>Count: {{ count }}</p>`,
})
export class CounterComponent implements OnInit {
count = 0;
private cdr = inject(ChangeDetectorRef);
private destroyRef = inject(DestroyRef);
ngOnInit() {
interval(1000)
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe(() => {
this.count++;
this.cdr.markForCheck();
});
}
}Two points are easy to miss. First, markForCheck() needs a pass to follow. In a zone-based app, the interval callback runs inside the Angular zone, so zone.js schedules a pass when the callback ends. If the callback ran outside the zone (for example under NgZone.runOutsideAngular), the flag would be set but nothing would run the pass. Second, markForCheck() is cheap and safe to call repeatedly. Several calls before one pass behave like one call.
5. Signals read in the template
When a template reads a signal, Angular records that dependency. If the signal's value changes, Angular marks that component's view for refresh. No markForCheck() is needed.
import { ChangeDetectionStrategy, Component, signal } from '@angular/core';
@Component({
selector: 'app-signal-counter',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<p>Count: {{ count() }}</p>
<button (click)="increment()">Add</button>
`,
})
export class SignalCounterComponent {
count = signal(0);
increment() {
this.count.update((c) => c + 1);
}
}The signal must be read during template evaluation. Reading it in a method that the template does not call, or copying its value into a plain field in the constructor, leaves the template with no dependency to track.
What does not mark the component
The following surprises people most often.
| Situation | Marks the OnPush component? | Why |
|---|---|---|
| Mutating an object passed as an input | No | The reference is unchanged |
| Pushing to an array passed as an input | No | Same reference |
| `setTimeout` or `setInterval` that sets a plain field | No | Not a template event; no marking call |
| HTTP response handled in `subscribe` that sets a field | No | Needs `markForCheck()` or a signal |
| Event on a sibling or on a parent's own element | No | Marks that element's own chain, not this component |
| Template event inside this component | Yes | Marks it and its ancestors |
| New value emitted to an `async` pipe | Yes | The pipe marks it |
| Signal read in template changes | Yes | Tracked dependency |
| `markForCheck()` | Yes | Explicit |
A useful check is to ask what told Angular. If you cannot name an input reference change, a template event, an async pipe, a signal, or a call to markForCheck(), the view will not update.
Marking is not the same as checking
Marking records that a check is needed. Checking happens during a pass. The order matters when you debug.
If you mark a component but no pass is scheduled, nothing renders. If a pass runs but nothing marked the component, the component is skipped. Both situations look the same on screen, a stale view, so identify which one you have before changing code.
Debugging a stale view
Work through these steps in order.
- Find the data the template shows and name the line of code that changes it.
- Ask how that line connects to the component. Is it an input assignment, a template event handler, an async pipe emission, a signal write, or none of these?
- If it is an input, check whether the parent replaces the object or mutates it.
- If it is none of these, check whether the change happens outside the Angular zone or in a callback that Angular does not know about.
- Add a temporary
markForCheck()after the change. If the view then updates, the missing piece was the notification, and you can replace the call with anasyncpipe or a signal.
You can also add a getter-based log in the template, such as {{ log() }} where log() calls console.log, to see how often a component is checked. Remove it afterward. Template function calls run on every check, which is itself a cost.
Edge cases
- First check. A new OnPush component is always checked once when it is created, even with no triggers. Static content works without any marking.
- Content projection. A projected child belongs to the component that declares it in its template, not to the component that hosts the
<ng-content>. Marking follows the declaring component. - Ancestors are marked, descendants are not. An event deep in the tree marks the path to the root. It does not mark unrelated OnPush components below those ancestors.
- Same value, new reference. Assigning
{ ...user }with identical content still counts as a change. Angular compares identity, not content, so it re-checks the child. - Setting inputs in code. Using
componentRef.setInput()marks an OnPush component. Assigning to a property directly oncomponentRef.instancedoes not.
Exercise
A child component uses OnPush and displays items.length from an input array items. The parent runs this.items.push('x') in a click handler. The child does not update. Name two different changes to the parent that would fix it, and explain why each works.
Show answer
Replace the array instead of mutating it, for example this.items = [...this.items, 'x']. The new reference makes the input binding differ from the previous value, so Angular marks the child for checking. Alternatively, hold the list in a signal in the parent and pass items() to the child after updating it with this.items.update(list => [...list, 'x']). The signal read changes the bound value to a new array, which also triggers the input check. (Calling markForCheck() in the child would not help here unless the child had been told that the data changed.)
Exercise
A component with OnPush subscribes in ngOnInit to an HTTP call and sets this.data = response in the callback. The template shows {{ data?.title }} and stays empty. List which trigger is missing and give two ways to fix it.
Show answer
No trigger fires: the callback is not a template event, there is no async pipe, no signal, and no input change. One fix is to inject ChangeDetectorRef and call markForCheck() after assigning this.data. Another is to expose the Observable as a field and use data$ | async in the template. A third option is to store the response in a signal and read it in the template.