Mat-form-field未包含MatFormFieldControl报错:mat-select用*ngIf出错如何解决
问题原因
Mat-form-field must contain a MatFormFieldControl错误触发的根本原因是:mat-form-field要求其内部必须始终存在实现了MatFormFieldControl接口的表单控件。你将*ngIf直接加在mat-select上,当exampleObject.innerObject为假值时,mat-select会被从DOM中移除,mat-form-field内部为空就会触发该错误。- 双向绑定时崩溃是因为当
exampleObject.innerObject(或你代码中对应的voipDc.hepic)为null/undefined时,直接读取其id属性会抛出空指针异常。
解决方案
根据你的需求(无对应数据时下拉显示空字段),可按以下步骤修改:
- 移除
mat-select上的*ngIf指令,保证mat-form-field内部始终存在表单控件,避免触发表单域空内容错误。 - 处理空对象问题,有两种可选方案:
- 方案一:在TS逻辑中初始化默认值,最推荐,模板写法更简洁
在拿到后端返回的exampleObject数据后,先做兜底初始化:
模板代码修改为:// 示例逻辑,可根据你的实际变量名调整 if (!this.exampleObject.innerObject) { this.exampleObject.innerObject = { id: null }; } // 对应你代码中的voipDc.hepic也做同样处理 if (!this.voipDc.hepic) { this.voipDc.hepic = { id: null }; }<mat-form-field appearance="legacy"> <mat-label>LOCATION</mat-label> <mat-select [(value)]="exampleObject.innerObject.id"> <!-- 新增空选项,无匹配数据时默认选中 --> <mat-option [value]="null"></mat-option> <ng-container *ngFor="let innerObject of arrays"> <mat-option [value]="innerObject.id">{{innerObject.location}}</mat-option> </ng-container> </mat-select> </mat-form-field> - 方案二:模板中拆分双向绑定,适配可选链取值
如果不想修改TS逻辑,可以把双向绑定拆成单向输入加事件输出,适配可选链避免空指针:<mat-form-field appearance="legacy"> <mat-label>LOCATION</mat-label> <mat-select [value]="exampleObject.innerObject?.id" (selectionChange)="exampleObject.innerObject && (exampleObject.innerObject.id = $event.value)"> <mat-option [value]="null"></mat-option> <ng-container *ngFor="let innerObject of arrays"> <mat-option [value]="innerObject.id">{{innerObject.location}}</mat-option> </ng-container> </mat-select> </mat-form-field>
- 方案一:在TS逻辑中初始化默认值,最推荐,模板写法更简洁
- 如果你确实需要在无数据时隐藏整个表单项,只需将
*ngIf移到mat-form-field标签上即可,也不会触发空控件错误:<mat-form-field *ngIf="exampleObject.innerObject" appearance="legacy"> <mat-label>LOCATION</mat-label> <mat-select [(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>
内容的提问来源于stack exchange,提问作者Hello Mr Mustafo
相关产品推荐
相关产品推荐

