Angular Material 组件 mat-select ngModel 未保留选定的选择

问题描述 投票:0回答:1

我使用 Angular Material

mat-select
组件进行了选择倍数。我的选项在下拉列表中正确显示,但所选值未保留在 UI 中。例如,在页面加载时
locationNameSelectedItems
返回 -

[{  
  id: 60  
  itemName: "Main Location - 1100 Superior Road"  
}]
<mat-form-field>
  <mat-select [(ngModel)]="locationNameSelectedItems" formControlName="locationName" multiple>
    <mat-option *ngFor="let location of locationNameDropdownList" [value]="location.id">{{location.itemName}}</mat-option>
  </mat-select>
</mat-form-field>

如何确保显示正确的选择?

angular angular-material
1个回答
0
投票

我有类似的情况,我想用 mat-selectmat-option 进行双向绑定,我用以下方法解决了。 这可能不是一个准确的解决方案,但这可能对您有帮助。

在 TypeScript 文件中提及模型对象

category: CategoryModel = {
   categoryId: 1,
   // other fields(if any)
};

然后在 HTML 模板中使用如下所示的片段代码,

<mat-select name="categoryId" [(ngModel)]="category.categoryId" required>
   <mat-option *ngFor="let categ of categories" [value]="categ.categoryId"> 
      {{ categ.categoryTitle }} 
   </mat-option>
 </mat-select>
    在我的例子中,
  • 类别是从后端获取的,您可以在TS文件中硬编码
  • 不要忘记将 name 属性赋予 mat-select 标签,其中名称应与要在对象中更新的字段相同。就我而言,它是 categoryId
  • 并在 mat-option 标签中使用 [value] 作为要在对象/模型中更新的对象的字段名称。
© www.soinside.com 2019 - 2024. All rights reserved.