7. Change Detection Deep Dive
Zone.js, OnPush, markForCheck, detectChanges, and how Angular decides what to re-render
You've used OnPush and the async pipe. But what's actually happening under the hood? How does Angular know when to check a component, and which components to skip? This article opens up the change detection engine — from Zone.js monkey-patching to the component tree traversal algorithm — so you can write faster apps and debug rendering issues with confidence.
What Change Detection Does
Every Angular app is a tree of components. Each component has a template that binds to data — {{ user.name }}, [class.active]="isActive", *ngFor="let item of items". When data changes, Angular needs to update the DOM to match.
Change detection is the process of walking the component tree, comparing current values to previous values, and updating the DOM where they differ. It runs synchronously, top-down, left-to-right — every time.
The two questions of change detection
1. When does it run? (What triggers a check?)
2. What gets checked? (Which components are visited?)
Zone.js answers the first question. Change detection strategy answers the second.
Zone.js: The Trigger
Angular doesn't poll for changes. Instead, it uses Zone.js — a library that monkey-patches every asynchronous browser API. Every setTimeout, setInterval, addEventListener, Promise.then, fetch, XMLHttpRequest, and requestAnimationFrame is wrapped so that Angular is notified when async work completes.
// What you write:
button.addEventListener('click', () => {
this.count++;
});
// What Zone.js turns it into (conceptually):
button.addEventListener('click', () => {
this.count++;
ngZone.onMicrotaskEmpty.emit(); // "something happened — run CD"
});
When Zone.js detects that all microtasks have drained, Angular calls ApplicationRef.tick(), which triggers change detection from the root component downward.
What triggers change detection
Every one of these runs change detection (in Default mode):
| Trigger | Example |
|---|---|
| DOM events | (click), (input), (keydown) |
| Timers | setTimeout, setInterval |
| HTTP responses | HttpClient subscriptions completing |
| Promises | Promise.then(), async/await |
| WebSocket messages | socket.onmessage |
requestAnimationFrame |
Animation loops |
This is why a simple setInterval(() => {}, 1000) causes Angular to check the entire component tree every second — even if nothing changed.
The Default Strategy: Check Everything
With ChangeDetectionStrategy.Default, Angular checks every component in the tree on every trigger. It walks top-down, evaluating every template binding in every component.
@Component({
selector: 'app-root',
template: `
<app-header></app-header>
<app-sidebar [items]="menuItems"></app-sidebar>
<app-main>
<app-user-list [users]="users"></app-user-list>
<app-footer></app-footer>
</app-main>
`
})
export class AppComponent { /* ... */ }
A click anywhere — even on a button inside app-footer — causes Angular to check the bindings in AppComponent, HeaderComponent, SidebarComponent, MainComponent, UserListComponent (including every *ngFor row), and FooterComponent. For every component, it evaluates every {{ }} expression, every [binding], every *ngIf and *ngFor.
In a small app, this is fine. In an app with hundreds of components and thousands of bindings, it becomes a performance bottleneck.
OnPush: Check Only What Changed
ChangeDetectionStrategy.OnPush tells Angular: skip this component unless one of these things happened:
- An
@Input()reference changed (shallow check —===) - A DOM event originated from this component (or a child)
- An Observable piped through
asyncemitted a new value markForCheck()was called on the component'sChangeDetectorRef- A Signal read in the template changed (Angular 17+)
If none of these conditions are true, Angular skips the component and its entire subtree.
@Component({
selector: 'app-user-card',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<div class="card">
<h3>{{ user.name }}</h3>
<p>{{ user.email }}</p>
</div>
`
})
export class UserCardComponent {
@Input() user!: User;
}
Why reference equality matters
With OnPush, Angular checks @Input() values using === (reference equality). Mutating an object in place does not trigger re-rendering:
// WRONG: mutation - OnPush won't detect this
this.user.name = 'Updated Name';
// RIGHT: new reference - OnPush will detect this
this.user = { ...this.user, name: 'Updated Name' };
This is why immutable data patterns (spread operators, Array.map instead of Array.splice) are essential in OnPush apps.
The Dirty-Checking Algorithm
Understanding the traversal order helps you reason about performance. Angular processes the component tree in two phases:
Phase 1: Mark dirty (bottom-up)
When a trigger occurs (input change, event, async pipe emission), Angular marks the component as dirty and walks up the tree to the root, marking each ancestor. This creates a "dirty path" from root to the changed component.
Phase 2: Check (top-down)
Angular then walks the tree top-down. At each node:
- If the component is not on a dirty path and uses OnPush, skip it and its subtree
- Otherwise, evaluate all template bindings
- If a binding value changed, update the DOM
- Continue to child components
Trigger: UserList receives new @Input()
Mark dirty (bottom-up):
UserList -> Main -> App (all marked dirty)
Check (top-down):
App -> dirty, check bindings
Header -> OnPush, NOT dirty -> SKIP
Sidebar -> OnPush, NOT dirty -> SKIP
Main -> dirty, check bindings
UserList -> dirty, check bindings, update DOM
Footer -> OnPush, NOT dirty -> SKIP
markForCheck() vs detectChanges()
These are two methods on ChangeDetectorRef that give you manual control over change detection.
markForCheck() — schedule a check
Marks the component and all its ancestors as dirty. The actual check happens in the next change detection cycle (usually triggered by Zone.js).
@Component({
changeDetection: ChangeDetectionStrategy.OnPush,
template: `<p>{{ message }}</p>`
})
export class NotificationComponent implements OnInit {
message = '';
constructor(
private cdr: ChangeDetectorRef,
private ws: WebSocketService
) {}
ngOnInit() {
// WebSocket messages arrive outside Angular's zone
this.ws.messages$.subscribe(msg => {
this.message = msg;
this.cdr.markForCheck(); // tell Angular: "I changed, check me next cycle"
});
}
}
Use markForCheck() when:
- You update component state from a callback that Angular doesn't know about
- You're using OnPush and need to signal that something changed
- You want to batch updates (multiple
markForCheck()calls in the same tick result in one check)
detectChanges() — check right now
Immediately runs change detection on this component and its children, synchronously. Does not wait for the next cycle.
@Component({
changeDetection: ChangeDetectionStrategy.OnPush,
template: `<canvas #canvas></canvas>`
})
export class ChartComponent {
@ViewChild('canvas') canvas!: ElementRef<HTMLCanvasElement>;
private animationId = 0;
constructor(
private cdr: ChangeDetectorRef,
private ngZone: NgZone
) {}
startAnimation() {
// Run outside Angular's zone to avoid triggering CD on every frame
this.ngZone.runOutsideAngular(() => {
const animate = () => {
this.updateCanvas();
// Only update Angular bindings when needed
if (this.needsTemplateUpdate) {
this.cdr.detectChanges();
}
this.animationId = requestAnimationFrame(animate);
};
animate();
});
}
}
Use detectChanges() when:
- You need the DOM updated immediately (not next cycle)
- You're running outside Angular's zone and need a synchronous render
- Performance-critical animation loops where you control exactly when to render
markForCheck vs detectChanges
markForCheck() | detectChanges() | |
|---|---|---|
| When it runs | Next CD cycle | Immediately (synchronous) |
| What it checks | This component + ancestors (marks dirty) | This component + children |
| Batching | Yes (multiple calls = one check) | No (each call runs immediately) |
| Common use | OnPush + external data | Outside-zone animations, immediate DOM reads |
Running Outside the Zone
For performance-critical code that doesn't need to trigger change detection — animation loops, frequent mouse-move handlers, WebSocket message processing — you can run code outside Angular's zone:
@Component({
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<div (mouseenter)="startTracking()"
(mouseleave)="stopTracking()">
<p>Position: {{ position.x }}, {{ position.y }}</p>
</div>
`
})
export class MouseTrackerComponent {
position = { x: 0, y: 0 };
private moveListener: (() => void) | null = null;
constructor(
private ngZone: NgZone,
private cdr: ChangeDetectorRef,
private el: ElementRef
) {}
startTracking() {
this.ngZone.runOutsideAngular(() => {
// This mousemove handler does NOT trigger change detection
const handler = (e: MouseEvent) => {
this.position = { x: e.offsetX, y: e.offsetY };
// Manually trigger CD at a throttled rate
this.cdr.detectChanges();
};
this.el.nativeElement.addEventListener('mousemove', handler);
this.moveListener = () =>
this.el.nativeElement.removeEventListener('mousemove', handler);
});
}
stopTracking() {
this.moveListener?.();
this.moveListener = null;
}
}
Without runOutsideAngular, every mouse movement would trigger full change detection. With it, Angular's zone is completely unaware of the events, and you control exactly when the template updates.
When to use NgZone.runOutsideAngular()
requestAnimationFrameloops (games, charts, animations)- High-frequency DOM events (
mousemove,scroll,resize) - Web Worker communication
- Third-party libraries that use timers or events internally (charting libs, map SDKs)
To re-enter the zone (e.g., when you need Angular to react to something):
this.ngZone.run(() => {
// This WILL trigger change detection
this.importantValue = newValue;
});
Zoneless Angular (Experimental)
Angular 18+ introduced experimental zoneless change detection, removing the Zone.js dependency entirely. Instead of patching async APIs, Angular relies on Signals and explicit notifications.
// app.config.ts
import { provideExperimentalZonelessChangeDetection } from '@angular/core';
export const appConfig: ApplicationConfig = {
providers: [
provideExperimentalZonelessChangeDetection()
]
};
In zoneless mode, change detection is triggered by:
- Signal value changes (read in templates)
markForCheck()callsAsyncPipeemissions- Component input changes
This removes the overhead of Zone.js and gives you complete control over when change detection runs. It pairs naturally with Signals, which is the topic of the next article.
Common Performance Pitfalls
1. Function calls in templates
<!-- BAD: called on EVERY change detection cycle -->
<p>{{ getFullName() }}</p>
<div *ngIf="isExpired()">Expired!</div>
<!-- GOOD: evaluated once and cached -->
<p>{{ fullName }}</p>
<div *ngIf="isExpired">Expired!</div>
Template expressions are re-evaluated on every CD cycle. A function call runs every time — even if its inputs haven't changed. Use properties, computed() signals, or pipes instead.
2. Missing trackBy on *ngFor
<!-- BAD: entire list is re-rendered on every change -->
<div *ngFor="let user of users">{{ user.name }}</div>
<!-- GOOD: only changed items are re-rendered -->
<div *ngFor="let user of users; trackBy: trackById">{{ user.name }}</div>
Without trackBy, Angular destroys and recreates DOM elements whenever the array reference changes — even if the items are the same.
3. Unnecessary setInterval / polling
// BAD: triggers CD every second, even if nothing changed
setInterval(() => this.checkSomething(), 1000);
// GOOD: run outside zone, only trigger CD when something actually changes
this.ngZone.runOutsideAngular(() => {
setInterval(() => {
const result = this.checkSomething();
if (result !== this.lastResult) {
this.lastResult = result;
this.cdr.markForCheck();
}
}, 1000);
});
4. Heavy computation in getters
// BAD: recalculated on every CD cycle
get sortedUsers(): User[] {
return [...this.users].sort((a, b) => a.name.localeCompare(b.name));
}
// GOOD: only recalculated when users change
private _sortedUsers: User[] = [];
updateUsers(users: User[]) {
this.users = users;
this._sortedUsers = [...users].sort((a, b) => a.name.localeCompare(b.name));
}
Or better yet, use a computed() signal or a pipe.
Profiling Change Detection
Angular DevTools
The Angular DevTools browser extension has a Profiler tab that shows:
- How many CD cycles ran
- How long each cycle took
- Which components were checked
- Which components actually changed
Manual profiling with ngDoCheck
@Component({
selector: 'app-expensive',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `...`
})
export class ExpensiveComponent implements DoCheck {
private checkCount = 0;
ngDoCheck() {
this.checkCount++;
console.log(`ExpensiveComponent checked ${this.checkCount} times`);
}
}
ngDoCheck is called on every CD cycle that reaches this component — even if nothing changed. It's a useful diagnostic to see how often a component is being checked.
Try It Yourself -- Change Detection Visualizer
Click on components to trigger events and watch change detection walk the tree. Toggle between Default and OnPush strategies to see how many components get checked.
Summary
| Concept | Purpose |
|---|---|
| Zone.js | Monkey-patches async APIs to trigger CD automatically |
| Default strategy | Checks every component on every trigger |
| OnPush strategy | Skips components unless inputs/events/async pipe say otherwise |
markForCheck() |
Marks dirty for the next cycle (batched, deferred) |
detectChanges() |
Runs CD immediately on this subtree |
runOutsideAngular() |
Runs code without triggering CD |
| Zoneless mode | Removes Zone.js; relies on Signals and explicit triggers |
Change detection is the engine that keeps your templates in sync with your data. Understanding it — and controlling it with OnPush, Signals, and zone management — is the difference between an Angular app that feels instant and one that stutters on every click.
What's Next
Angular's newest reactivity primitive — Signals — changes the change detection story fundamentally. Instead of Zone.js watching everything, Signals tell Angular exactly which template bindings changed. The next article covers signal(), computed(), effect(), and how Signals interop with the RxJS world you already know.