【问题标题】:Bind value to html select将值绑定到 html 选择
【发布时间】:2019-01-24 08:28:24
【问题描述】:
我尝试将值绑定到 html 选择。它工作得很好,除非值已经设置,它不会在选择中被选中。
<div class="col-md-1">
<label class="search-label">{{'AUDIT_LOG_SEARCH_METHOD_DEVICE_TYPE' | translate}}</label>
<select class="form-control" [(ngModel)]="searchModel.request_device_type"
id="device_id" name="device_id" #device_id="ngModel">
<option *ngFor="let item of auditLogDeviceTypeItems" [ngValue]="item">{{item.text}}</option>
</select>
</div>
我做错了什么?
【问题讨论】:
标签:
html
angular
data-binding
【解决方案1】:
<div class="col-md-1">
<label class="search-label">{{'AUDIT_LOG_SEARCH_METHOD_DEVICE_TYPE' | translate}}</label>
<select class="form-control id="device_id" name="device_id" #device_id="ngModel">
<option *ngFor="let item of auditLogDeviceTypeItems" [ngValue]="item" [selected]="searchModel.request_device_type == item">{{item.text}}</option>
</select>
</div>
由于您没有提供驻留在变量中的完整数据结构,这是我能想到的解决方案。请根据您的要求进行调整。
【解决方案2】:
你可以试试这个解决方案。
我在Stackblitz创建了一个演示
使用 [compareWith]="compareObjects" 在选择中使用对象
component.html
<select name="role" [compareWith]="compareObjects" [(ngModel)]="searchModel.request_device_type">
<option *ngFor="let r of auditLogDeviceTypeItems" [ngValue]="r">{{r.name}}</option>
</select>
组件.ts
searchModel = {
request_device_type: { "id": 1, "name": "user" }
}
auditLogDeviceTypeItems = [
{ "id": 1, "name": "user" },
{ "id": 2, "name": "admin" }
]
compareObjects(o1: any, o2: any): boolean {
return o1.id === o2.id && o1.name === o2.name;
}