Angular Error Explained: Expression Changed After It Has Been Checked Error

A colleague of mine encounters an error message while developing an Angular frontend app. The error message is like this:

ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value 'null', Current value: 'true'.

The scenario for this error is when he’s developing a back button feature from the second page to the first page, where the first page is already rendered before, and need to re-render second time with different initial values.

The reason for this error is because, after each operation, Angular remembers what values it used to operate. They are stored in the oldValues property of the component view. After the checks have been done for all components, Angular then starts the next digest cycle, but instead of operating, it compares the current values with the ones it remembers from the previous digest cycle.

Note that this additional checking is only performed in the development mode. Angular enforce so-called unidirectional data flow from top to bottom. No component lower in the hierarchy is allowed to update the properties of a parent component after parent changes have been processed.

The possible solution of the above issues includes using async update, such as setTimeout or force change detection at ngAfterViewInit() with _changeDetectorRef.detectChanges(), where the ChangeDetectorRef class has the following 5 methods:

abstract class ChangeDetectorRef {
abstract markForCheck(): void
abstract detach(): void
abstract detectChanges(): void
abstract checkNoChanges(): void
abstract reattach(): void
}

So you can run change detection and update child view. My colleague was happy the error got resolved then after this explanation.


Originally published at https://victorleungtw.com on September 7, 2020.

By Victor Leung

Experience in software development, consulting services and technical product management. Understanding of business and technology with an MBA in Finance and a Master degree in Computer Science. AWS Certified Solution Architect with experience in building products from scratch and serving as a charismatic leader.

Leave a comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.