Select 默认 value/object 选项

Select default value/object option

我有这个显示所有产品类别的 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 文件)进行添加。

解决方案是使用如下 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;
  }