0

当我*ngIf在内部设置条件时出现此错误<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>

我的问题是当对象 id 为空时,它在数据库中不存在。我想在下拉列表中显示一个空字段,但它在这一行崩溃了[(value)]="voipDc.hepic.id"

4

1 回答 1

0

使用时<mat-form-field>,表单域控件必须在其中。如表格字段中所述 | Angular Material > 错误:mat-form-field 必须包含 MatFormFieldControl

更新:删除了以前的版本,因为[(value)].

您可以使用&&运算符来检查两者是否都exampleObject.innerObject具有exampleObject.innerObject.id价值。

这类似于可选链接以逃避潜在的属性是nullundefined停止访问嵌套属性。

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

StackBlitz 上的示例解决方案

于 2021-10-21T09:23:30.110 回答