I have a simple Angular component, that on rendering throw the following error:
MyComponent.html:10 ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked.
Previous value: 'ngForOf: [object Map Iterator]'.
Current value: 'ngForOf: [object Map Iterator]'.
The error is thrown twice, even when moved to a bare-minimum Angular project with no other code (just an AppComponent wrapping this component).
I minimized the code to the most minimal form that still reproduces the problem. I replaced the data service with a hardcoded observable.
Component
@Component({
selector: 'my-component',
templateUrl: './my.component.html',
styleUrls: ['./my.component.scss'],
})
export class MyComponent implements OnInit, OnDestroy {
private cobs: Map<number, string>;
private cobSub: Subscription;
constructor() {}
ngOnInit() {
// originally data comes from a service...
this.cobSub = of(new Map<number, string>([[1, 'a'], [2, 'b']]))
.subscribe({
next: cobs => { this.cobs = cobs; },
});
}
ngOnDestroy(): void {
this.cobSub.unsubscribe();
}
}
Note that asyncPipe is more common for use in this sort of scenario - but I cannot use it.
Template
<div>
<table *ngIf="cobs">
<tr>
<th>Id</th>
<th>Class of Business</th>
</tr>
<tr *ngFor="let key of cobs.keys()">
<td>{{key}}</td>
<td>{{cobs.get(key)}}</td>
</tr>
</table>
</div>
Why is the problem happening?
How it can be fixed?