#Change detection in Angular

2 messages · Page 1 of 1 (latest)

shell meadow
#

Why in Angular, when I added this button:
https://shorturl.at/fvS4j

I got this error: Error: NG0100: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value for 'disabled': 'false'. Current value: 'true'.

Here is the code for the onChangePasswordNeed() handler:
https://shorturl.at/SnTxu

After calling the onChangePasswordNeed() function, I set validators for the form controls newPasswordControl and confirmNewPasswordControl. And after passing through console.log('form.invalid', this.form.invalid); it shows "false" in the console. But it should be "true" because I added validators and now the fields are empty and should have at least one error - they are required but currently empty. After calling this method, I got an error. However, after clicking on this button:

<button (click)="status()">
  Check [disabled] is true or false
</button>

the status() handler code:

status() {
  console.log(this.form.invalid);
}

it showed "true" in the console log result. So why didn't it show this to me immediately after I updated the controls (added validators)?

The [disabled] value in the template:

<button [disabled]="form.invalid" class="btn btn-primary" type="submit">Update</button>

I just want to understand why this happened and how it works. Please explain in detail or provide where I can read about this.

For example:
I added this in the onChangePasswordNeed() code:
https://shorturl.at/HHLTS
form.invalid 1 showed FALSE, then form.invalid 2 showed TRUE. What exactly does the detectChanges() method do that it changes the form.invalid status? As far as I know, detectChanges should update the data that has changed to display it correctly in the template, but here it somehow updates the form status. So why doesn't it do this automatically, and I have to call it manually and If I don't I will get the error.

Gist

GitHub Gist: instantly share code, notes, and snippets.

Gist

GitHub Gist: instantly share code, notes, and snippets.

Gist

GitHub Gist: instantly share code, notes, and snippets.

frail crystal
#

That error typically occurs when some component is being instantiated and inserted into the dom. Does it happen when the button is clicked?