How Angular change detection works, and when OnPush helps
You can build Angular apps for a long time without thinking about change detection.
You can build Angular apps for a long time without thinking about change detection. Then one screen gets slow, or a value refuses to show up, and suddenly you need to know how Angular decides what to update.
Who tells Angular that something changed?
Angular doesn’t watch your variables. It relies on Zone.js, which patches pretty much every async API in the browser: setTimeout, promises, addEventListener, XHR and so on. Whenever one of those callbacks finishes, Zone.js lets Angular know, and Angular runs change detection.
So a click, an HTTP response and a timer all end the same way. Angular walks the component tree from the root down and checks every binding in every template. If a value differs from last time, it updates the DOM.
That’s why a plain assignment just works:
loadUser() {
this.http.get<User>('/api/me').subscribe((user) => {
this.user = user; // no setState, no notify, it just shows up
});
}
It’s convenient. It also means a single mousemove listener can make Angular check the whole app dozens of times a second.
What a check costs
For each component, Angular evaluates every expression in the template and compares it with the previous value. Reading a property is cheap. Calling a function isn’t free, because it runs on every check:
@Component({
selector: 'app-cart',
template: `<p>Total: {{ total() }}</p>`,
})
export class CartComponent {
items: Item[] = [];
total() {
return this.items.reduce((sum, i) => sum + i.price * i.qty, 0);
}
}
total() runs whenever anything in the app triggers change detection. With a handful of items you won’t notice. Inside a big *ngFor it adds up. A pure pipe is the usual fix, because Angular only runs it again when its input changes:
@Pipe({ name: 'cartTotal' })
export class CartTotalPipe implements PipeTransform {
transform(items: Item[]): number {
return items.reduce((sum, i) => sum + i.price * i.qty, 0);
}
}
<p>Total: {{ items | cartTotal }}</p>
A pure pipe compares its input by reference, though, so pushing into the same items array won’t re-run it. The same idea comes back with OnPush below.
One more thing: in development mode Angular runs a second check right after the first, to make sure nothing changed in between. That’s where ExpressionChangedAfterItHasBeenCheckedError comes from. Production builds skip that second pass, so don’t judge performance in dev mode.
OnPush
ChangeDetectionStrategy.OnPush tells Angular it can skip a component, and everything under it, unless there’s a reason to check it.
@Component({
selector: 'app-user-card',
template: `
<h3>{{ user.name }}</h3>
<p>{{ user.email }}</p>
`,
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class UserCardComponent {
@Input() user!: User;
}
An OnPush component gets checked when:
- one of its @Inputs receives a new reference,
- an event fires in its own template or a child’s template,
- an async pipe in its template gets a new value,
- you call markForCheck().
The first point trips up almost everyone. This won’t update the card:
renameMutating() {
this.user.name = 'Asha K'; // same object, so the card is skipped
}
Angular compares inputs with ===. It’s still the same object, so as far as the card can tell, nothing happened. Give it a new object instead:
rename() {
this.user = { ...this.user, name: 'Asha K' };
}
So OnPush nudges you toward immutable data, which is a good habit anyway.
markForCheck vs detectChanges
If an OnPush component gets data from a subscription, a new value isn’t one of the triggers above. The async pipe takes care of that for you:
@Component({
selector: 'app-price',
template: `<span>{{ price$ | async }}</span>`,
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class PriceComponent {
price$ = this.prices.updates$;
constructor(private prices: PriceService) {}
}
If you subscribe yourself, you have to tell Angular:
ngOnInit() {
this.sub = this.prices.updates$.subscribe((p) => {
this.price = p;
this.cdr.markForCheck();
});
}
markForCheck() marks the component and its ancestors as dirty, so they’re checked in the next cycle. detectChanges() is different: it runs change detection right away, for this component and its children. I use markForCheck() nearly every time. detectChanges() is for the rare case where the DOM must be updated before the next line of code runs.
Running outside Angular
Some listeners shouldn’t trigger change detection at all: drag handles, canvas drawing, scroll tracking. NgZone.runOutsideAngular registers them outside the zone, and you step back in only when the UI really needs to change.
constructor(private zone: NgZone) {}
ngOnInit() {
this.zone.runOutsideAngular(() => {
window.addEventListener('mousemove', this.onMove);
});
}
ngOnDestroy() {
window.removeEventListener('mousemove', this.onMove);
}
private onMove = (e: MouseEvent) => {
if (e.buttons === 1) {
this.zone.run(() => {
this.x = e.clientX;
this.y = e.clientY;
});
}
};
Without this, every mouse move would mean a full check of the app.
Where to start
If a screen feels slow, profile it with Angular DevTools before changing anything. The usual suspects are function calls in templates, a long *ngFor without trackBy, and chatty event listeners. After that, switch list items and leaf components to OnPush. You don’t have to convert the whole app at once, because OnPush and Default components work fine side by side.