我尝试将值绑定到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>
我在做什么错了?
答案 0 :(得分: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>
由于您没有提供驻留在变量中的完整数据结构,因此这是我能想到的解决方案。请根据您的要求进行调整。
答案 1 :(得分:0)
您可以尝试使用此解决方案。
我已经在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>
component.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;
}