Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ExpressionChangedAfterItHasBeenCheckedError when using ReactiveForms and NgbModal

I have a reactive form and when the user presses the ESC key in an input i would like to show an "are you sure" modal before the form gets hidden.
As soon as the modal is shown i get the following exception in the console:

ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has 
changed after it was checked. Previous value: 'ng-untouched: true'. Current 
value: 'ng-untouched: false'.

Here is a stackblitz that shows the issue (focus input and press ESC)

Note: When you focus the input, blur and focus again the issue wont appear as ng-untouched wont change again.

Is there any workaround? Whats the recommended way to implement such a functionality?

Thanks in advance!

like image 776
bys Avatar asked Dec 13 '18 13:12

bys


People also ask

What is expressionchangedafterithasbeencheckederror in angular?

What is ExpressionChangedAfterItHasBeenCheckedError? The ExpressionChangedAfterItHasBeenCheckedError error is thrown up when the binding expression changes after being checked by Angular during the change detection cycle.

What is aftercontentchecked in angular?

AfterContentChecked is triggered when angular finishes checking of the projected content. Hence if you are using these hooks, you should make sure that they do not change any binding that angular has already checked. Better to avoid using these hooks as angular invokes them during every change detection cycle.

What is expression changed after it was checked?

Angular Examples & Projects The expression has changed after it was checked (Expressionchangedafterithasbeencheckederror) is one of the common errors, that we encounter in Angular applications. The error arises when the binding expression changes after angular checked it during the change detection cycle.

What is expressionchangedafterithasbeencheckederror trying to warn me about?

What Is ExpressionChangedAfterItHasBeenCheckedError Trying to Warn Me About? ExpressionChangedAfterItHasBeenCheckedError is thrown when an expression in your HTML has changed after Angular has checked it (it is a very expressive error).


2 Answers

I finally found a way to overcome the issue but still having the dirty flag maintained.

ng-untouched is maintained onBlur when FormControl is set to {updateOn:'change'} (the default). What you have to do is simply blur the input manually before opening the modal. When the modal is shown it will blur anyway.

Here is a stackblitz

like image 76
bys Avatar answered Sep 20 '22 03:09

bys


Try this:

this.form = new FormGroup({
  test: new FormControl('',{updateOn:'submit'})
})
like image 43
Chellappan வ Avatar answered Sep 20 '22 03:09

Chellappan வ