Sub topic 3
Opting in with ChangeDetectionStrategy.OnPush
The previous chapter showed that default change detection checks every component in the tree on every pass. This chapter covers the switch that changes that for one component: ChangeDetectionStrategy.OnPush. It explains what the setting changes, how to turn it on, and how it affects lifecycle hooks and the components around it. It also shows the first stale view you are likely to hit.
You should already be comfortable with these topics:
- Standalone components, templates, and data binding.
@Inputand@Output.- Basic RxJS subscriptions.
- The difference between mutating an object and replacing it with a copy.
The chapters that follow cover each OnPush trigger in detail, so this one only names them.
What the setting changes
Under default change detection, every pass walks the whole component tree. Angular re-evaluates every template binding in every component and updates the DOM wherever a value differs from last time.
OnPush gives a component's view a dirty flag. During a pass, Angular checks that component's view and everything beneath it only when the flag is set. Otherwise it skips the entire subtree, and no binding in it is evaluated.
A view is flagged dirty in these cases:
- The component is created. Its first check always happens.
- A template binding passes a different input reference.
- An event listener in its template, or a host listener on it, runs.
- Something calls
markForCheck(). The async pipe does this when a value arrives. - A signal read in its template changes.
After a check, Angular clears the flag. The component then stays untouched until one of these happens again.
The opt-in is a trade. You give up the guarantee that "any change anywhere refreshes everything", and in return Angular does less work. The component must now be written so that every change it needs to show arrives through one of the routes above.
Enabling it
Set changeDetection in the component decorator:
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;
}The setting is a single line, and it changes nothing about how the component is written otherwise. Its template, inputs and outputs work as before. What changes is when Angular looks at it.
You can make the Angular CLI set it for you. To generate one component with the strategy:
ng generate component user-card --change-detection=OnPushTo make OnPush the default for every component the CLI generates in a project, add this to the project's entry in angular.json (excerpt):
{
"projects": {
"my-app": {
"schematics": {
"@schematics/angular:component": {
"changeDetection": "OnPush"
}
}
}
}
}This only affects newly generated components. Existing components keep whatever strategy they declare.
The setting is per component
changeDetection applies to the component that declares it. Children do not inherit it, and a Default child does not turn its parent's skipping off.
The diagram shows one pass after a click handler runs in the root component. The Dashboard view is clean.
Chart is a Default component, yet it is not checked. Angular never descends into Dashboard's view, so Chart's strategy never comes into play. A component's strategy decides whether its own view is refreshed when its parent is checked. It does not override a skip higher up.
This works the other way too. If a component deep in the tree is marked for checking, for example by an event inside it, Angular also marks its ancestors dirty up to the root. The pass can then reach it. A dirty OnPush leaf therefore updates correctly even when its ancestors are OnPush and otherwise clean.
Lifecycle hooks under OnPush
Skipping a view does not skip every hook. These are the rules for the common ones:
| Hook | When it runs on an OnPush component |
|---|---|
| `ngOnChanges` | Only when a bound input receives a new value. |
| `ngOnInit` | Once, on creation, as usual. |
| `ngDoCheck` | Whenever the parent view is checked, even if this component's own view is skipped. |
ngDoCheck is the hook that lets a component notice changes that OnPush would otherwise hide, such as in-place mutation of an input. Keep it cheap, because it runs on every parent pass. If you find yourself writing a comparison in ngDoCheck to keep an OnPush component fresh, treat that as a sign the data flow should change. Replacing immutable values or using signals is usually a better fix.
Seeing the skip
To confirm that a component is skipped, log from a template expression. This is a debugging aid only, so remove it afterwards.
import { ChangeDetectionStrategy, Component, Input } from '@angular/core';
@Component({
selector: 'app-price-tag',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `<p>{{ amount }} {{ logCheck() }}</p>`,
})
export class PriceTagComponent {
@Input({ required: true }) amount!: number;
logCheck(): string {
console.log('PriceTag view checked');
return '';
}
}Now place it in a Default parent:
import { Component } from '@angular/core';
import { PriceTagComponent } from './price-tag.component';
@Component({
selector: 'app-dashboard',
imports: [PriceTagComponent],
template: `
<button (click)="clicks = clicks + 1">Clicked {{ clicks }}</button>
<app-price-tag [amount]="19.99" />
`,
})
export class DashboardComponent {
clicks = 0;
}Load the page and you see the log line from the first check. Click the button and Clicked increments, but PriceTag view checked does not appear again. The parent was checked, and the child's amount is the same literal, so its flag stayed clear. If you remove changeDetection from PriceTagComponent, every click logs a new line.
In development mode Angular runs a second verification pass after each check. You may therefore see two log lines per check. Compare the counts before and after a click rather than relying on the absolute number.
The first stale view
OnPush is safe only when every change the component displays reaches it through a trigger. This component breaks that rule:
import { ChangeDetectionStrategy, Component } from '@angular/core';
@Component({
selector: 'app-delayed-label',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `<p>{{ label }}</p>`,
})
export class DelayedLabelComponent {
label = 'Loading...';
constructor() {
setTimeout(() => {
this.label = 'Ready';
}, 1000);
}
}The first check renders Loading.... One second later the timer callback changes label. In an app using Zone.js, the callback ends and Angular starts a new pass. But the component's flag is clear, so the pass skips it. The field now holds Ready while the screen still shows Loading....
Under default change detection this code works, which is why moving a component to OnPush can look like a regression. Nothing in the component is wrong in the plain-JavaScript sense. The view just was never told to refresh.
You have three ways to tell it, and later chapters cover each in turn:
- Expose the value as an Observable and bind it with the async pipe.
- Call
markForCheck()after the change. - Store the value in a signal and read it in the template.
Migrating an existing component
Moving a component to OnPush is a small edit followed by an audit of how its data changes. A practical order:
- Add
changeDetection: ChangeDetectionStrategy.OnPushto the decorator. - List every field the template reads. For each one, ask what changes it: an input, a template event, a subscription, a timer, or a service call.
- For a field changed by an input, check that the parent replaces the object instead of mutating it. The next chapter covers this.
- For a field changed by a template event, no work is needed. The event marks the view dirty.
- For a field changed anywhere else, route it through the async pipe, a signal, or
markForCheck(). - Run the app and exercise each path. A path that was missed shows up as a view that updates late or only after an unrelated click.
Start with leaf components that take simple inputs and have few asynchronous sources. They are the easiest to get right, and they stop the most work for the effort. Containers that wire up services are better left until you are confident with the triggers.
Edge cases
| Situation | What happens |
|---|---|
| Default child inside a clean OnPush parent | The child is skipped with its parent. |
| Event handler in a Default child of an OnPush parent | The event marks the child and its ancestors dirty, so the update shows. |
| Input bound to a literal, such as `[amount]="19.99"` | The reference never changes, so the input never triggers a recheck after the first one. |
| Field changed in `setTimeout`, `fetch`, or a manual subscription | No trigger fires. The view stays stale until another trigger arrives. |
| Parent is checked but no input changed | `ngDoCheck` runs on the child, and its view is skipped. |
Key points
changeDetection: ChangeDetectionStrategy.OnPushgives a component a dirty flag. Angular checks the view and its subtree only when the flag is set.- The strategy is per component and is not inherited. A skipped parent skips all of its descendants, whatever their own strategy.
- A newly created component is always checked once.
- Marking a descendant dirty marks its ancestors dirty too, so the pass can reach it.
ngDoCheckstill runs on the child whenever the parent is checked.- Any change that does not arrive through an input, a template event,
markForCheck(), the async pipe, or a signal leaves the view stale.
Exercise
A Default component Panel contains an OnPush component Table. Table contains a Default component Row. A timer callback in Panel changes a field that only Row displays through a service call, and nothing marks any view dirty. After the next pass, is Row refreshed? What would change if the user clicked a button inside Row?
Show answer
Row is not refreshed. The pass reaches Table, whose flag is clear, so Angular skips Table and everything under it, including the Default Row. A click on a button inside Row runs an event listener in Row's template. That marks Row dirty and also marks its ancestor Table dirty, so the next pass reaches Row and refreshes it.
Exercise
In DelayedLabelComponent, the label stays on "Loading..." after one second. Name the three ways to get "Ready" onto the screen, and say why the same code works under default change detection.
Show answer
Use an Observable with the async pipe, call markForCheck() after assigning the field, or store the label in a signal that the template reads. It works under default change detection because Angular checks every component on each pass. The pass that follows the timer callback re-evaluates {{ label }} and finds the new value.