Sub topic 11
Why ExpressionChangedAfterItHasBeenChecked happens
This chapter assumes you know Angular components, template bindings, lifecycle hooks such as ngOnInit and ngAfterViewInit, and the order in which Angular checks a component tree. It builds on the previous chapters about the change detection cycle and the Default and OnPush strategies.
What the error says
In development mode, Angular sometimes stops with this message:
NG0100: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed
after it was checked. Previous value: 'waiting'. Current value: 'hello'.The message means that Angular evaluated a template binding, stored the result, and later found a different result for the same binding in the same change detection run. Angular treats this as a bug in your code because it breaks the rule that data flows down the tree in one pass.
The rule behind the error
A change detection cycle walks the component tree from the root downward. For each view, Angular does these things in order:
- It evaluates the view's template bindings and compares each value with the one stored from the previous run.
- It writes any changed values to the DOM.
- It sets the inputs of child components and runs their
ngOnChanges,ngOnInitandngDoCheckhooks. - It checks the child views.
- It runs the
ngAfterViewInitandngAfterViewCheckedhooks.
A parent's bindings are therefore evaluated before its children are checked. Once the parent's DOM is written, Angular does not go back. If a child, or a hook that runs late in the cycle, changes state that the parent already displayed, the DOM shows the old value while the component holds a new one.
To catch this, Angular runs a second pass in development mode. This pass is often called checkNoChanges. It walks the tree again, re-evaluates every binding, and compares the result with the value stored a moment earlier. It never updates the DOM. It only verifies that the first pass was consistent, and it throws if any value differs.
The check applies to every binding: interpolation, property bindings, @if and @for expressions, and structural directive inputs. Angular compares values with Object.is, except that the development-mode comparison is lenient for objects and arrays. Two different object references do not fail by themselves, and arrays are compared element by element. In practice the error almost always reports a string, number or boolean.
A minimal reproduction
The parent below reads a value from its child in ngAfterViewInit and stores it in a field that its own template displays.
import { Component } from '@angular/core';
@Component({
selector: 'app-child',
template: `<p>Child is ready</p>`,
})
export class Child {
greeting = 'hello';
}import { AfterViewInit, Component, ViewChild } from '@angular/core';
import { Child } from './child';
@Component({
selector: 'app-parent',
imports: [Child],
template: `
<p>Child says: {{ message }}</p>
<app-child />
`,
})
export class Parent implements AfterViewInit {
message = 'waiting';
@ViewChild(Child) child!: Child;
ngAfterViewInit() {
this.message = this.child.greeting; // changes a value the template already rendered
}
}The sequence of events is:
- Angular evaluates
{{ message }}as'waiting'and writes it to the DOM. - Angular creates and checks the child.
ngAfterViewInitsetsmessageto'hello'.- The verification pass evaluates
{{ message }}again, gets'hello', and throws.
The child view is not available until after the parent's own bindings have been evaluated. That is why the hook runs this late.
Common causes
The same ordering problem shows up in several forms:
- A late hook writes state that the template reads. Examples are
ngAfterViewInit,ngAfterContentInitandngAfterViewChecked, as shown above. - A child changes parent state during its own check. For example, a child's
ngOnInitcalls a method on a shared service, and the service changes a field that the parent has already rendered. Settingloading = falsethis way is common. - A getter or method returns a different value on each call. Examples are
get now() { return Date.now(); }andget id() { return Math.random(); }. The second evaluation never matches the first. - A binding depends on something later in the template. A template reference such as
{{ panel.isOpen }}may be evaluated before the component that ownsisOpenchanges it. - Form and router state changes during a check. Examples are a validator or
valueChangessubscription that updates a displayed flag while the view is being checked.
Fixing it
The best fixes move state so that data flows downward, from owner to consumer, in a single pass. The workarounds below only defer or force a second pass.
| Fix | How it works | Trade-off |
|---|---|---|
| Move the data to the owner | The parent owns the value and passes it down as an input, so nothing flows upward during the check. | Best option. It may need a small restructure. |
| Compute earlier | Set the value in `ngOnInit` or the constructor, before the template is evaluated. | Works only if the data is available that early. |
| Derive the value | Use `computed` from other signals so the value is a function of state, not an assignment made in a hook. | Needs signal-based state. |
| Call `detectChanges()` after the write | Re-checks this component's view immediately, so the stored value matches. | Adds an extra check. Overuse hides design problems. |
| Defer the write with `setTimeout`, `Promise.resolve().then` or `queueMicrotask` | The change happens after the current cycle, and Zone.js schedules a new cycle. | Causes an extra cycle and a brief stale frame. Without Zone.js, a plain field write schedules nothing, so the new value needs a signal or `markForCheck()`. |
For the example above, the cleanest fix is to give the data to the parent in the first place, so nothing is read back from the child.
import { Component, input } from '@angular/core';
@Component({
selector: 'app-child',
template: `<p>Child got: {{ greeting() }}</p>`,
})
export class Child {
greeting = input.required<string>();
}import { Component } from '@angular/core';
import { Child } from './child';
@Component({
selector: 'app-parent',
imports: [Child],
template: `
<p>Child says: {{ greeting }}</p>
<app-child [greeting]="greeting" />
`,
})
export class Parent {
greeting = 'hello';
}Both bindings read greeting in the same top-down pass, and nothing changes it afterwards, so the verification pass agrees.
When the data really is produced late, for example by a child that measures its own size, detectChanges() is an acceptable local fix:
import { AfterViewInit, ChangeDetectorRef, Component, ViewChild, inject } from '@angular/core';
import { Child } from './child';
@Component({
selector: 'app-parent',
imports: [Child],
template: `
<p>Child says: {{ message }}</p>
<app-child />
`,
})
export class Parent implements AfterViewInit {
private cdr = inject(ChangeDetectorRef);
message = 'waiting';
@ViewChild(Child) child!: Child;
ngAfterViewInit() {
this.message = this.child.greeting;
this.cdr.detectChanges(); // re-evaluate this view now, so the stored value is 'hello'
}
}This version assumes the Child class from the first example, which has a plain greeting field.
Diagnosing a report
When the error appears, work through these steps:
- Read the message. The previous and current values usually identify the binding, and the stack trace names the component whose template contains it.
- Find what writes to that value. Look first for
ngAfterViewInit,ngAfterContentInit,ngAfterViewChecked, subscriptions that fire synchronously during a check, and getters with side effects. - Check whether the writer runs after the reader in the cycle. If a child or a late hook changes parent state, the order is the cause.
- Choose the fix: move the data to the owner, compute it earlier, derive it, or force a re-check.
- Reload and confirm the error is gone, and confirm that the DOM shows the correct value in both a development and a production build.
Exercise
A component template contains {{ now }}, and the class defines get now() { return Date.now(); }. The page works in a production build but throws NG0100 in development. Why, and how would you fix it?
Show answer
In development, Angular runs a verification pass after the normal check and re-evaluates every binding. The getter returns a different number each time, so the second value differs from the one stored in the first pass and Angular throws. Production skips the verification pass, so the error is hidden, though the DOM can show a slightly stale time. To fix it, store the timestamp in a field, for example one set in ngOnInit or updated by a timer that triggers its own change detection run, and bind the template to that field.
Exercise
A child component's ngOnInit calls this.layout.setTitle('Report'). The service updates a title field that the parent's template displays before the <app-child /> tag. Why does this throw, and what is one fix that avoids a second check?
Show answer
The parent's {{ title }} binding is evaluated first and written to the DOM. The child is created and initialized afterwards, and its ngOnInit changes title. The verification pass then sees a different value for the same binding and throws. A fix that avoids a second check is to set the title before the parent's template is evaluated, for example in the parent's own ngOnInit or in a route resolver, so the data flows down in one pass.