Sub topic 6
Custom change checks with ngDoCheck
This chapter assumes you know how @Input() bindings work, how ngOnChanges and ngOnInit behave, and the basics of change detection from the previous chapters. You should also be comfortable with TypeScript classes and with the difference between a reference and a value.
What ngDoCheck is
ngDoCheck is a lifecycle hook that Angular calls during every change detection pass for a component or directive. It runs right after ngOnChanges and ngOnInit on the first pass. On later passes it runs right after ngOnChanges, which Angular calls only if an input reference changed.
ngDoCheck runs even when no input changed. It is the only hook that lets you run your own comparison logic before Angular checks the component's template.
import { Component, DoCheck } from '@angular/core';
@Component({
selector: 'app-probe',
standalone: true,
template: `<p>Probe</p>`,
})
export class ProbeComponent implements DoCheck {
ngDoCheck(): void {
console.log('ngDoCheck ran');
}
}Why ngOnChanges is not always enough
ngOnChanges fires only when the reference bound to an input changes. Angular compares the old and new values with Object.is. If a parent mutates an object or array in place, the reference stays the same and ngOnChanges does not fire.
// Parent code: same array reference, new content
this.items.push('new item'); // ngOnChanges in the child will NOT fireThere are two common fixes. The first is to have the parent produce a new reference, for example this.items = [...this.items, 'new item']. This is usually the better design. The second is to let the child detect mutations itself with ngDoCheck. Use the second when you do not control the parent, or when the data structure is mutable by design.
Detecting mutations with KeyValueDiffers and IterableDiffers
Angular provides differs for this purpose. A differ stores a snapshot of an object or collection and reports what changed since the last check. KeyValueDiffers handles objects and maps. IterableDiffers handles arrays and other iterables.
import { Component, DoCheck, Input, IterableDiffer, IterableDiffers, inject } from '@angular/core';
@Component({
selector: 'app-item-log',
standalone: true,
template: `
<ul>
@for (line of log; track $index) {
<li>{{ line }}</li>
}
</ul>
`,
})
export class ItemLogComponent implements DoCheck {
@Input() items: string[] = [];
log: string[] = [];
private readonly differs = inject(IterableDiffers);
private differ: IterableDiffer<string> = this.differs.find([]).create();
ngDoCheck(): void {
const changes = this.differ.diff(this.items);
if (changes) {
changes.forEachAddedItem((record) => {
this.log.push(`added: ${record.item}`);
});
changes.forEachRemovedItem((record) => {
this.log.push(`removed: ${record.item}`);
});
}
}
}The call this.differ.diff(this.items) returns null when nothing changed. When something changed, it returns a DefaultIterableDiffer object, which you can inspect with methods such as forEachAddedItem and forEachRemovedItem. The first call after creation reports every existing item as added.
For objects, the pattern is the same with KeyValueDiffers:
import { Component, DoCheck, Input, KeyValueDiffer, KeyValueDiffers, inject } from '@angular/core';
@Component({
selector: 'app-settings-watch',
standalone: true,
template: `<p>Changes seen: {{ changeCount }}</p>`,
})
export class SettingsWatchComponent implements DoCheck {
@Input() settings: Record<string, unknown> = {};
changeCount = 0;
private readonly differs = inject(KeyValueDiffers);
private differ: KeyValueDiffer<string, unknown> = this.differs.find({}).create();
ngDoCheck(): void {
const changes = this.differ.diff(this.settings);
if (changes) {
changes.forEachChangedItem(() => this.changeCount++);
changes.forEachAddedItem(() => this.changeCount++);
changes.forEachRemovedItem(() => this.changeCount++);
}
}
}The differs compare keys and top-level values only. A nested object that is mutated in place does not show up as a change on its parent.
A hand-written comparison
You do not have to use a differ. For a small piece of state, a manual comparison is clearer. Keep the previous value in a private field and compare it to the current one.
import { Component, DoCheck, Input } from '@angular/core';
interface Filter {
text: string;
includeArchived: boolean;
}
@Component({
selector: 'app-filter-view',
standalone: true,
template: `<p>Applied {{ applyCount }} times</p>`,
})
export class FilterViewComponent implements DoCheck {
@Input() filter: Filter = { text: '', includeArchived: false };
applyCount = 0;
private lastText = '';
private lastArchived = false;
ngDoCheck(): void {
if (
this.filter.text !== this.lastText ||
this.filter.includeArchived !== this.lastArchived
) {
this.lastText = this.filter.text;
this.lastArchived = this.filter.includeArchived;
this.applyCount++;
}
}
}Copy the values you compare. Storing only a reference to the same mutable object would make the comparison always equal.
How often it runs
ngDoCheck runs once per change detection pass of the component's host view, not once per user action. Any event, timer, or resolved promise handled inside Angular's zone can start a pass. With the default change detection strategy, every component is visited on every pass.
This frequency is the main constraint on what you can do inside the hook. A slow ngDoCheck slows down every interaction in the application. Keep the body to cheap comparisons, and never do network calls, deep clones, or heavy loops there.
OnPush and ngDoCheck
A component with ChangeDetectionStrategy.OnPush is skipped during a pass unless an input reference changed, an event fired in its template, or it was marked dirty. Its own ngDoCheck still runs, because Angular calls it as part of checking the parent's view. This is what makes ngDoCheck useful in OnPush components: you can detect an in-place mutation and then ask Angular to check the view.
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, DoCheck, Input, inject } from '@angular/core';
@Component({
selector: 'app-tag-list',
standalone: true,
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<ul>
@for (tag of tags; track tag) {
<li>{{ tag }}</li>
}
</ul>
`,
})
export class TagListComponent implements DoCheck {
@Input() tags: string[] = [];
private readonly cdr = inject(ChangeDetectorRef);
private lastLength = 0;
ngDoCheck(): void {
if (this.tags.length !== this.lastLength) {
this.lastLength = this.tags.length;
this.cdr.markForCheck();
}
}
}Here markForCheck() flags the component and its ancestors so that the template is refreshed in this pass. The comparison compares only the length, so replacing one tag with another would be missed. For real code, use a differ or compare contents.
Pitfalls and edge cases
- Expensive work. The hook runs on every pass. Deep equality checks on large structures can cause visible lag.
- State changes that affect the parent. Changing a value the parent already rendered in the same pass can trigger
ExpressionChangedAfterItHasBeenCheckedin development mode. Change only the component's own state. - Using it for first-time setup.
ngDoCheckis not an initialization hook. Put one-time setup inngOnInit. - Sharing a differ between inputs. A differ keeps the snapshot of one object. Create one differ per tracked input.
- Signals. If the data is a signal, you do not need
ngDoCheck. Acomputedoreffectreacts to signal changes directly, and the chapter on signals covers this. - Reaching for it too soon. Immutable updates in the parent and
ngOnChangescover most cases with less cost.
Choosing an approach
| Situation | Preferred tool |
|---|---|
| Parent can pass a new reference | `ngOnChanges` |
| Parent mutates an array in place | `ngDoCheck` with `IterableDiffers` |
| Parent mutates an object in place | `ngDoCheck` with `KeyValueDiffers` or a manual comparison |
| State is held in signals | `computed` or `effect` |
Exercise
A child component receives @Input() items: string[]. The parent calls items.push('x') and the child's ngOnChanges never runs. Why, and name two ways to make the child react?
Show answer
ngOnChanges fires only when the input reference changes, and push mutates the same array. One fix is for the parent to assign a new array, such as this.items = [...this.items, 'x'], which triggers ngOnChanges. The other is for the child to implement ngDoCheck and use an IterableDiffer (or compare the contents manually) to detect the mutation.
Exercise
Why must the body of ngDoCheck stay cheap, and why can an OnPush component still use it to detect mutations?
Show answer
Angular calls ngDoCheck on every change detection pass, so slow code there slows every interaction in the app. An OnPush component's view can be skipped, but its ngDoCheck still runs as part of checking the parent's view. The hook can detect a mutation and call markForCheck() so the component's template is refreshed.