我有一组对象(名为 users),它们将显示为 dropdownlist
的选项。我还有另一个对象列表(名为 selectedUsers 并保存在后端)用于初始化 dropdownlist
。
数组:
users = [
{
id: 2,
name: 'name2'
},{
id: 2,
name: 'name2'
},{
id: 3,
name: 'name3'
}
];
selectedUsers3 = [
{
id: 1,
name: 'name1'
},{
id: 2,
name: 'name2'
}
];
我正面临一种有线情况,即当我通过 [ngValue]
将 Object
绑定(bind)到 select options
,并将一个函数绑定(bind)到[selected]
将检查当前选项是否存在于 selectedUsers
中。
我可以看到函数已被检索并且结果返回 true/false,但选项保持未选中状态。
模板:
<select multiple [(ngModel)]="selectedUsers3">
<option *ngFor="let user of users" [selected]="checkExist(user)" [ngValue]="user">{{user.name}}</option>
</select>
组件中的函数:
checkExist(user) {
return this.selectedUsers3.findIndex(selUser => selUser.id === user.id) > -1;
//return this.selectedUsers3.filter(selUser => selUser.id === user.id).length > 0;
}
提到我用Array.filter
或Array.findIndex
检查数据是否存在,结果是正确的。
请引用这个demo使用第三个 dropdownlist
,检查我哪里做错了?还是我遗漏了有关 [selected]
的内容?我希望有人能解释清楚这一点。
更新:
在@Günter Zöchbauer 的帮助下,无论是single select
还是 multi select
,但我仍然很困惑,为什么他们一起工作得很好,但一起失败,并且仍在试图找出原因。
最佳答案
selected
不支持 [(ngModel)]="selectedUser3"
。
要选中某个项目,value
(仅适用于字符串)或 ngValue
属性值需要与 selectedUser3
中的值匹配。
this.selectedUser3 = this.users[2];
默认情况下只检查对象标识,因此具有相同属性和值的另一个对象实例不匹配。
您可以使用 compareWith
https://angular.io/docs/ts/latest/api/forms/index/SelectControlValueAccessor-directive.html
<select [compareWith]="compareFn" [(ngModel)]="selectedCountries"> <option *ngFor="let country of countries" [ngValue]="country"> {{country.name}} </option> </select> compareFn(c1: Country, c2: Country): boolean { return c1 && c2 ? c1.id === c2.id : c1 === c2; }
关于Angular:在与 ngModel 一起使用时,在 select 的选项上选择不能正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44044746/