Unexpected Angular ExpressionChangedAfterItHasBeenCheckedError in template-driven form

136 Views Asked by At

I have a very simple Angular Component as follow:

import { Component } from '@angular/core';

@Component({
  selector: 'test-view',
  template: `
    <div [ngStyle]="{ 'background-color': m.invalid ? 'red' : 'green'}">{{m.status}}</div>
    <input #m="ngModel" type="text" [ngModel]="val" required/>
  `
})
export class TestViewComponent {
  val = 'test';
}

This example is very similar to the official Angular documentation for template driven forms (https://angular.io/guide/forms#show-and-hide-validation-error-messages).

When I run it using Angular 14.2 in debugging mode, the following error is displayed:

ERROR Error: NG0100: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'green'. Current value: 'red'. Find more at https://angular.io/errors/NG0100

If I remove the required attribute from the input field or I invert the order of the div and input tags, the exception disappears.

What I am doing wrong?

1

There are 1 best solutions below

0
On

That's typical error for Angular development, it occurs when you try to change any initial value on initialization proceess. Secondary check (works only in development mode) works on AfterViewInit hook. Because of that you catch the error.

A simple solution here is to trigger change detection process in AfterViewInit hook. Like this:

ngAfterViewInit(): void {
    this.cdRef.detectChanges();
}

But you should know this error means you're doing something wrong with your data initialization. Better is to recheck your data and prevent change values within init hooks.