Search code examples
angularangular-material2

Mat-select with *ngIf causing ExpressionChangedAfterItHasBeenCheckedError


I have a mat-form-field which I want to contain an input or a select.

When I use an < input > the *ngIf works fine. However, when I use a < mat-select > like below it throws the 'ExpressionChangedAfterItHasBeenCheckedError'.

I think this has only started happening since I've updated my angular versions to:

Angular CLI: 8.2.1
Node: 10.16.2
Angular: 9.0.0-next.1

Why should it work with an input and not a select?

Here is the html:

<mat-form-field>
  <input *ngIf="input.name!=='Bid'" matInput [(ngModel)]="input.value">
  <mat-select *ngIf="input.name==='Bid'" [(value)]="input.value">
    <mat-option *ngFor="let s of statuses" name="status" [value]="s">{{s}}</mat-option>
  </mat-select>
  <mat-placeholder class="placeholder">{{input.name}}</mat-placeholder>
</mat-form-field>

The input.name properties are set in a method called in the ngOnInit() like so:

ngOnInit() {
  this.prepareInputs();
}

Solution

  • This was caused by the <mat-placeholder> line, which did not have the *ngIf applied to it, so when the input was not chosen, the <mat-placeholder> was causing things to jam up! When I put the *ngIf on the <mat-placeholder> the problem disappeared.

    <mat-form-field>
      <input *ngIf="input.name!=='Bid'" matInput [(ngModel)]="input.value">
      <mat-placeholder *ngIf="input.name!=='Bid'" class="placeholder">{{input.name}}</mat-placeholder>
      <mat-select *ngIf="input.name==='Bid'" [(value)]="input.value">
        <mat-option *ngFor="let s of statuses" name="status" [value]="s">{{s}}</mat-option>
      </mat-select>
    </mat-form-field>