2023-12-31

Angular 17 - ExpressionChangedAfterItHasBeenCheckedError thrown despite calling detectChanges

I'm experiencing a slight issue with Angular and its change detection. I've got a very simple form that allows for additional input containers to be added, and yet every time I click the add button I get an ExpressionChangedAfterItHasBeenCheckedError thrown in the console. When using a standard ngFor the error is thrown in the console, but the new input is still displayed. However, when using Angular's new @for option I get the error thrown in the console, but it also isn't displayed. In both scenarios I made sure to call a detectChanges (also tried markForCheck), but it made no difference.

  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></span>
        </ng-container>
      </div>

I'd greatly appreciate any insight into the issue, thanks in advance.

I've tried using both an ngFor as well as Angular's new @for option, the only difference between the two is that when using the @for the new data isn't displayed in addition to the console error. I've also attempted calling the change detector manually but it had no impact.



No comments:

Post a Comment