选择默认值/对象选项

时间:2018-05-02 09:51:53

标签: angular5 html-select

我有这个select元素,显示所有产品类别。

<div class="form-group">
   <label class="control-label">Category</label> 
   <select (ngModelChange)="setNewCategory($event)" [(ngModel)]="product.productCategory" name="productCategory">
   <option *ngFor="let category of productCategoriesPage?.content" [ngValue]="category">{{category.name}}</option>
   </select>
</div>

如果我想编辑产品,我希望在select option元素中预先选择其类别。是否有一些东西要添加到HTML代码中,或者这应该以编程方式(ts文件)。

1 个答案:

答案 0 :(得分:0)

解决方案是使用compareWith指令,如下所示:

<select [compareWith]="compareFn" (ngModelChange)="setNewCategory($event)" [(ngModel)]="product.productCategory" name="productCategory">

并且:

compareFn(pc1: ProductCategory, pc2: ProductCategory): boolean {
    return pc1 && pc2 ? pc1.id === pc2.id : pc1 === pc2;
  }