I'm encountering a minor problem with Angular and its change detection mechanism. I have created a simple form where additional input fields can be added dynamically. However, every time I click the add button, an
ExpressionChangedAfterItHasBeenCheckedError
is thrown in the console.
When I use a regular ngFor loop, the error appears in the console but the new input field is still displayed. On the other hand, when I utilize Angular's new @for
directive, the error shows up in the console and the new input field does not appear on the screen.
I have tried calling both detectChanges
and markForCheck
, but it did not resolve the issue.
public properties: Map<number, string> = new Map<number, string>();
public addProperty() {
const id: number = this.properties.size ?
Array.from(this.properties.keys()).reduce((a, b) => a > b ? a : b) + 1 : 1;
this.properties.set(id, 'placeholder');
this.changeDetectorRef.detectChanges();
}
<button class="btn btn-primary" (click)="addProperty()">+</button>
<div class="d-flex flex-column">
<ng-container *ngFor="let attribute of properties.entries()">
<span>{{ attribute[0] }}</span>
</ng-container>
</div>
Any help to address this issue would be highly appreciated. Thank you in advance.
I have experimented with both ngFor
and Angular's new @for
, and found that the main difference is that the data added using @for
is not displayed along with the console error.
I also attempted manual change detection without success.