Sub topic 5
How change detection drives the hooks
This chapter assumes you know what each hook is called and roughly what it is for. It also assumes you can read a standalone component with @Input bindings. Here you will learn what actually causes Angular to call the hooks, and why a hook sometimes does not run when you expect it to.
Hooks are a by-product of a check pass
Angular does not call hooks on a schedule. Hooks run while Angular performs change detection, the process of walking the component tree and updating the DOM so it matches component state. Each pass is called a tick, and it has three steps:
- Something tells Angular that state may have changed.
- Angular starts at the root component and walks down the tree, in order.
- As it processes each template, it updates bindings, calls hooks, and refreshes child views.
Creation hooks such as the constructor run once, when the component is instantiated. Every other hook, apart from ngOnDestroy, is tied to a tick. This explains a common surprise. If no tick happens, ngOnChanges, ngDoCheck and the Checked hooks do not run.
What starts a tick
By default, Angular uses Zone.js. This library patches browser APIs, so Angular finds out when an event handler, timer, or HTTP callback has finished. Angular then runs a tick. With zoneless change detection (opt-in through provideZonelessChangeDetection()), nothing patches the browser. Instead, a tick is scheduled when a signal read by a template changes, when markForCheck() is called, or when an event listener in a template fires.
| Trigger | Zone-based app | Zoneless app |
|---|---|---|
| Template event listener (`(click)`) | Tick after the handler | Tick after the handler |
| `setTimeout`, `setInterval` callback | Tick after the callback | No automatic tick |
| Signal read in a template changes | Tick (the zone is also running) | Tick |
| `ApplicationRef.tick()` called by hand | Tick | Tick |
If a value changes in a callback that triggers no tick, the screen does not update and the hooks do not run. This happens, for example, in a timer callback in a zoneless app that sets a plain field.
The order inside one pass
For each component, Angular follows the same sequence while it processes the parent's template. The parent's template update sets the child's inputs first, and the child's own template is refreshed afterwards.
Three details follow from this order:
- Inputs are assigned before any hook of that component runs. This is why the constructor sees empty inputs and
ngOnInitsees real values. ngOnChangesruns only if at least one input binding produced a different value than last time. Angular compares with===, so it compares object references, not their contents.- The
Inithooks run once, on the first pass, and theCheckedhooks andngDoCheckrun on every pass.
Default and OnPush components
The walk above visits every component on every tick when the strategy is Default. With ChangeDetectionStrategy.OnPush, Angular can skip a component's own view. It refreshes that view only when the component is marked dirty:
- An input binding received a new reference.
- An event listener in the component's own template ran.
markForCheck()was called, which theasyncpipe does for you.- A signal that the template reads changed.
Skipping the view does not skip every hook. The parent's template processing still runs ngDoCheck on the OnPush child, because that hook is called from the parent's side of the pass. The child's template is the only part that is skipped. The following example makes the difference visible.
import {
ChangeDetectionStrategy,
Component,
DoCheck,
Input,
OnChanges,
SimpleChanges,
} from '@angular/core';
interface User {
name: string;
}
@Component({
selector: 'app-badge',
standalone: true,
changeDetection: ChangeDetectionStrategy.OnPush,
template: `<p>Badge: {{ user.name }}</p>`,
})
export class BadgeComponent implements OnChanges, DoCheck {
@Input({ required: true }) user!: User;
ngOnChanges(changes: SimpleChanges): void {
console.log('badge ngOnChanges', Object.keys(changes));
}
ngDoCheck(): void {
console.log('badge ngDoCheck, user.name =', this.user.name);
}
}
@Component({
selector: 'app-parent',
standalone: true,
imports: [BadgeComponent],
template: `
<button (click)="mutate()">Mutate</button>
<button (click)="replace()">Replace</button>
<app-badge [user]="user" />
`,
})
export class ParentComponent {
user: User = { name: 'Ada' };
mutate(): void {
this.user.name += '!';
}
replace(): void {
this.user = { name: this.user.name + '!' };
}
}Click Mutate and the console shows badge ngDoCheck with the new name, but no ngOnChanges. The user reference is the same, so the input counts as unchanged. The button belongs to the parent's template, so the badge is not marked dirty, and its text on screen still shows the old name. Click Replace and you get ngOnChanges, then ngDoCheck, and the screen updates.
Why ngDoCheck and the Checked hooks must stay cheap
ngDoCheck, ngAfterContentChecked and ngAfterViewChecked run on every tick. In a large tree, one tick can call them hundreds or thousands of times. Typing in an input box may trigger a tick for each keystroke. Work that is slow or allocates a lot in these hooks directly slows down the whole application.
Follow these rules:
- Compare small values, such as a length or a version number, and do nothing when they match.
- Do not make HTTP calls, write to the DOM, or create subscriptions in these hooks.
- Do not change state that the template already read in this pass. This is the cause of the next section's error.
The dev-mode verification pass
In development builds, Angular runs a second pass after each tick, called checkNoChanges. It re-reads every binding and compares it with the value it rendered a moment ago. If a value differs, Angular throws ExpressionChangedAfterItHasBeenChecked. The error means that a hook or getter changed state after the template had already used it. A child's ngAfterViewInit that sets a field the parent has already rendered is a typical example. Production builds skip this pass, so the template silently shows stale data instead of an error.
The usual fixes move the state change out of the pass. Compute the value before the parent's template reads it, or use a signal so that Angular schedules another tick. A later chapter covers these in detail.
A mental checklist
When a hook does not behave as you expect, ask these questions in order:
- Did a tick happen at all? Check whether the trigger is one that Angular sees.
- Was the component skipped because of OnPush? If so,
ngDoCheckstill runs, and the view does not. - Did the input reference change?
ngOnChangesignores mutations inside an object. - Is the hook one that runs once (
Init) or on every pass (Checked,ngDoCheck)?
Exercise
In the BadgeComponent example, you click Mutate three times. How many times does ngOnChanges run, how many times does ngDoCheck run (counting only these three clicks), and does the text on screen change?
Show answer
ngOnChanges runs zero times, because the user reference never changes. ngDoCheck runs three times, once per tick, because the parent's template is processed on every tick even though the badge is OnPush. The text on screen does not change, because the click handler is in the parent's template, so the OnPush badge is not marked dirty and its view is skipped.
Exercise
A default-strategy component sets this.count++ inside a setTimeout callback in an app that uses zoneless change detection, and the template shows {{ count }} from a plain field. The number never updates. Why, and what is the smallest fix?
Show answer
Without Zone.js, nothing tells Angular that the timer callback ran, and a plain field is not a signal, so no tick is scheduled and no check hooks run. The smallest fix is to make count a signal (count = signal(0) and this.count.update(c => c + 1), with {{ count() }} in the template), which schedules a tick when its value changes.