Sub topic 4
The change detection cycle, top to bottom
This chapter assumes you know how components, templates and bindings fit together (covered earlier in this tutorial). It also assumes you can read basic TypeScript and know that Zone.js is what notices asynchronous work finishing. Here you will follow one complete change detection cycle: what starts it, which order Angular visits the tree in, which lifecycle hooks run when, and why Angular runs a second verification pass in development.
One cycle is one walk of the tree
A change detection cycle is a single pass over the component tree. Angular reads the current value of every binding in each template it visits and compares it with the value it stored during the previous cycle. If a value differs, Angular updates the DOM node tied to that binding. If nothing differs, it does not touch the DOM.
In an application using Zone.js, the cycle is started by ApplicationRef.tick(). Zone.js tells Angular that a task finished: an event handler ran, a timer fired, a promise resolved, or an HTTP callback arrived. Once the zone has no queued microtasks left, Angular calls tick(). Zone.js is only the trigger. The cycle described here is the same no matter what starts it.
The cycle has these properties:
- It starts at the root component and moves downward. A parent is always processed before its children.
- Each component's view is visited once per cycle. Siblings are visited in template order.
- Data is expected to flow one way, from parent to child. A component should not change state that a component earlier in the walk has already rendered.
- It reads and compares values. It does not track which assignment changed a property. This is why a plain
this.count++is noticed at all: Angular comparescountagainst the stored value on the next visit.
What happens inside one view
Each component has a view, which is its template compiled into two functions: one that creates DOM nodes the first time, and one that updates bindings on every cycle. Refreshing a view runs a fixed sequence of steps.
- Run the template's update function. This evaluates each binding expression in this template and compares the result with the stored value. Changed property bindings are written to the DOM, and changed inputs are written to child component instances.
- Run
ngOnChanges(only if an input changed),ngOnInit(first cycle only) andngDoCheckon the child directives and components found in this template. These are called as the update function reaches each one. - Update content queries, then run
ngAfterContentInit(first cycle only) andngAfterContentCheckedfor those children. - Refresh the view of each child component. This repeats this same sequence one level down.
- Update view queries, then run
ngAfterViewInit(first cycle only) andngAfterViewChecked.
The key point is that a parent's bindings are evaluated before any child view is refreshed. By the time Angular enters a child's template, the child's inputs already hold their new values. After all children finish, the "view" hooks fire on the way back up, so a parent's ngAfterViewChecked runs after every descendant has been checked.
Watching the order in code
The following example logs every hook. Create the three files below, bootstrap App as usual, and read the console.
// child.ts
import {
AfterContentChecked,
AfterContentInit,
AfterViewChecked,
AfterViewInit,
Component,
DoCheck,
Input,
OnChanges,
OnInit,
} from '@angular/core';
@Component({
selector: 'app-child',
template: `<p>{{ log('template') }}</p>`,
})
export class Child
implements OnChanges, OnInit, DoCheck, AfterContentInit, AfterContentChecked, AfterViewInit, AfterViewChecked
{
@Input() label = '';
log(step: string): string {
console.log(`${this.label} ${step}`);
return this.label;
}
ngOnChanges() { this.log('ngOnChanges'); }
ngOnInit() { this.log('ngOnInit'); }
ngDoCheck() { this.log('ngDoCheck'); }
ngAfterContentInit() { this.log('ngAfterContentInit'); }
ngAfterContentChecked() { this.log('ngAfterContentChecked'); }
ngAfterViewInit() { this.log('ngAfterViewInit'); }
ngAfterViewChecked() { this.log('ngAfterViewChecked'); }
}// app.ts
import { AfterViewChecked, Component, DoCheck } from '@angular/core';
import { Child } from './child';
@Component({
selector: 'app-root',
imports: [Child],
template: `
<app-child [label]="'A'" />
<app-child [label]="'B'" />
`,
})
export class App implements DoCheck, AfterViewChecked {
ngDoCheck() { console.log('App ngDoCheck'); }
ngAfterViewChecked() { console.log('App ngAfterViewChecked'); }
}// main.ts
import { bootstrapApplication } from '@angular/platform-browser';
import { App } from './app';
bootstrapApplication(App).catch((err) => console.error(err));During the first cycle the order is:
App ngDoCheckA ngOnChanges,A ngOnInit,A ngDoCheckB ngOnChanges,B ngOnInit,B ngDoCheckA ngAfterContentInit,A ngAfterContentChecked, then the same two hooks for BA template, thenB template, because each child view is refreshed in turnA ngAfterViewInit,A ngAfterViewChecked, then the same two hooks for BApp ngAfterViewChecked
On a later cycle the Init hooks and ngOnChanges (the inputs are the same string literals) are skipped. ngDoCheck, the two Checked hooks and the template reads still run.
How the comparison works
For each binding, Angular stores the last value in a slot of the view's data array. On the next cycle it evaluates the expression again and compares the new result with the stored one using Object.is. The consequences:
- Primitives compare by value.
5against5is unchanged. - Objects and arrays compare by reference. Mutating
user.namedoes not change the reference stored for[user]="user", so the input is not considered changed. This does not stop{{ user.name }}in the same template from updating, because that binding's expression evaluates to a string that differs. NaNequalsNaNunderObject.is, so a binding that staysNaNis not rewritten every cycle.- A method call or getter in a template is evaluated on every cycle, because Angular has no way to know in advance whether it would return something different.
The last point is why the log call in the example prints once per visit of the template. Expensive methods in templates cost time on every cycle in which their view is checked.
The second pass in development mode
In development mode, Angular runs an extra step after every cycle: checkNoChanges. It walks the tree again, re-evaluates every binding, and compares each result with the value it just rendered. It writes nothing to the DOM. If any binding now yields a different value, Angular throws ExpressionChangedAfterItHasBeenCheckedError.
The check exists because the cycle is a single top-to-bottom pass. Suppose a child's ngAfterViewInit modifies a property that the parent's template already displayed. The parent's text was rendered before the change, and the walk will not return to it. The screen would show a stale value while the component holds a different one. The second pass detects this mismatch and reports it instead of leaving the inconsistency hidden. A later chapter covers fixing these errors in detail.
Production builds skip this pass, which means the check costs time only in development. The bug it detects still exists in production, where it shows up as a view that silently lags behind its state.
Cycles do not loop
Angular does not repeat the cycle until values settle. If a hook changes state after the relevant view has been rendered, Angular does not render it again in the same cycle. Your change is picked up the next time something triggers a cycle, or it causes the error above in development.
You can see this in the cycle's design. Changes made before a view is visited, such as in ngOnInit or in an event handler, are safe, because the walk reads them when it arrives. Changes made after a view was visited, such as a child modifying parent state in ngAfterViewInit, come too late.
What a cycle costs
The work in a cycle is proportional to the number of bindings in the views visited, plus the cost of every method call and ngDoCheck implementation in those views. With the Default strategy, every view in the tree is visited on every cycle, even if the event that triggered it concerned only one component. Large trees with many bindings make this visible as slow event handling. The next chapters show how to let Angular skip subtrees, and how to avoid starting cycles that do not need to happen.
Exercise
A parent template contains <app-child [items]="items" />. In the same cycle, in what order do the parent's ngAfterViewChecked, the child's ngOnChanges, and the child's ngAfterViewChecked run, and why must the parent's value come last?
Show answer
The order is the child's ngOnChanges, then the child's ngAfterViewChecked, then the parent's ngAfterViewChecked. The parent's template update writes the new items value into the child and triggers ngOnChanges before the child's own view is refreshed. The child's view hooks run after its view is refreshed. The parent's view hooks run only once all of its child views have been refreshed, so the parent's ngAfterViewChecked comes last.
Exercise
A component sets this.title = 'Loaded' inside ngAfterViewInit, and title is displayed in the same component's template. Why does development mode throw ExpressionChangedAfterItHasBeenCheckedError, and where could the assignment move to avoid it?
Show answer
The template was already rendered with the old title before ngAfterViewInit ran. The development-only checkNoChanges pass then evaluates {{ title }} again, finds a different value than the one just rendered, and throws. Moving the assignment to ngOnInit or the constructor sets the value before the template is first evaluated, so the first render and the verification pass agree.