Angular 4 EXCEPTION: Expression has changed after it was checked.

Sho Mukai
2 min readAug 24, 2017

--

From last week I am trying to use Angular 4 Reactive forms to implement a dynamic form based on JSON configuration.

Articles I have referenced:

Angualr Reactive Forms

Configurable Reactive Forms in Angular with dynamic components

In both articles, we already know how the form looks like, so we can generate the form group from the beginning. But in our case, we have to add some new or remove some fields based on user inputs. So we don’t know what the whole form looks like when we render the it… :(

Then we got the exception saying: Expression has changed after it was checked. — because we added some new controls after the form is binded in the template.

Apparently, Angular 4 is running a check (ngOnChanges) first, and then run ngOnInit. If you change any value that has binded with the template in one check cycle (like ngOnInit), that means you will get the Expression has changed exception, which is exactly what the expcetion tries to say…

In the real development process, we may do that a lot, because the sometimes we need the @Input binds and then decide what the other value may look like in ngOnInit.

On the internet, there seems to be two solutions:

1 Wrap the change to a setTimeout() for next tick.

2 Trigger a manual change detection by this.changeDetectionRef.detectChanges();

Both can solve the issue. But the second one seems to be more elegant and it solves our problem. :)

By the way, some posts are saying detectChanges() are consuming more memory, which seems to be ture. So be careful when using it.

Happy components :)

--

--

Sho Mukai
Sho Mukai

Written by Sho Mukai

Coder :) @TeamForm — helping teams to thrive

No responses yet