我正在尝试使用 [selected] 和 [ngValue] 设置包含表单中对象的选择标签的默认值。但出于某种原因,它们似乎不相容。
示例代码:
<select id="selectedStore" *ngIf="showStore"
class="form-control"
formControlName="homeStore"
tabindex="{{getTabIndex('homeStore')}}">
<option *ngFor="let store of availableStores"
[ngValue]="store"
[selected]="store.storeId == personalInfo.homeStore?.storeId">
{{store.name}}
</option>
</select>
此代码最终仅显示空白作为默认值。如果我删除 [ngValue] 它工作正常,除了然后它是被选中的 store.name 值,而不是商店对象。
有什么建议吗?
最佳答案
您可以将 compareWith
与 [ngValue]
一起使用
例如:
<select id="selectedStore" *ngIf="showStore"
class="form-control"
formControlName="homeStore"
tabindex="{{getTabIndex('homeStore')}}" [compareWith]="compareByID">
<option *ngFor="let store of availableStores"
[ngValue]="store">
{{store.name}}
</option>
</select>
compareByID(itemOne, itemTwo) {
return itemOne && itemTwo && itemOne.ID == itemTwo.ID;
}
参见:https://github.com/angular/angular/pull/13349
示例比较选择选项:http://blog.ninja-squad.com/2017/03/24/what-is-new-angular-4/
注意:此支持是在 Angular4 中添加的
关于html - 在 select 标签中使用 [ngValue] 和 [selected],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41299247/