[Angular] ExpressionChangedAfterItHasBeenCheckedError

Ying Tung Wu
2 min readNov 2, 2020

--

There are many ways to cause this exception. One of them is by generating components dynamically. In this case, I use PrimeNG to generate TabView with data bound to a FormControl object.

PrimeNG- Dynamic Tabs.

I use ListBox with multiple selection for user to choose which tabs they want to show on UI. When they select or deselect the items, tabs would be automatically generated. But when I tried to deselect item in order to make the shown tab disappears, it showed this error message on debug console. (Actually, we can also observe update latency on UI.)

Debug Console
ExpressionChangedAfterItHasBeenCheckedError

The reason why we have this exception is because of the value in FormControl has changed by background logic which caused inconsistent status of component. (Reference)

The concept of solution is simple — Update component status when value changes. In this case, we can simply use ChangeDetectorRef to force another change detection cycle to handle update of component for us. We can hook this handling in ngOnInit or ngAfterViewInit. Both can reach the same result.

ChangeDetectorRef

After adapting this solution, exception was gone. We can no longer observe update latency of UI. Problem solved. 👏👏👏

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Ying Tung Wu
Ying Tung Wu

Written by Ying Tung Wu

0 Followers

On the path of learning more.

No responses yet

Write a response