Home > Software design >  Mat-form-field must contain a MatFormFieldControl Error, Using *ngIf
Mat-form-field must contain a MatFormFieldControl Error, Using *ngIf

Time:10-22

I'm getting this error when I set *ngIf condition inside <mat-select>.

<mat-form-field appearance="legacy">
    <mat-label>LOCATION</mat-label>
    <mat-select *ngIf="exampleObject.innerObject"  [(value)]="exampleObject.innerObject.id">
        <ng-container *ngFor="let innerObject of arrays">
            <mat-option [value]="innerObject.id">{{innerObject.location}}</mat-option>
        </ng-container>
    </mat-select>
</mat-form-field>

My problem is when object id is null, it doesn't exist in DB. I want to show an empty field in the dropdown list, but it's crashing on this line [(value)]="voipDc.hepic.id".

CodePudding user response:

When you use <mat-form-field>, form-field control must be within it. As stated in Form field | Angular Material > Error: mat-form-field must contain a MatFormFieldControl.

Updated: Removed previous version as Optional Chaining not supported in [(value)].

You can use && operator to check whether both exampleObject.innerObject and exampleObject.innerObject.id have value.

This works similarly to optional chaining to escape potential property was null or undefined and stop accessing the nested property.

<mat-select
  [(value)]="exampleObject.innerObject && exampleObject.innerObject.id"
>
  ...
</mat-select>

Sample Solution on StackBlitz

  • Related