DEV Community

Victor Leung
Victor Leung

Posted on • Originally published at Medium on

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'.
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (1)

Collapse
 
carlosabud profile image
Carlos A.

You may also set the changeDetectionStrategy to "OnPush". This can also help solving this problem.