来自API的对象:
roles = {
admin: false,
user: true,
}
模板:
<mat-select formControlName="roles" required multiple [compareWith]="compareRoles">
<mat-option *ngFor="let role of roleList" [value]="role">{{role}}</mat-option>
</mat-select>
零件:
this.roles = ['admin', 'user']
createForm(): FormGroup
{
return this._formBuilder.group({
roles : [[this.roles]],
})
}
compareWith功能:
public compareRoles(c1: any, c2: any): boolean {
return true
}
compareWith函数的预期行为始终返回true:应检查'admin'和'user'。
实际行为:仅选中“admin”。函数不执行“用户”检查。
为什么只比较我的角色数组中的第一个值?另外,当compareWith函数总是返回true时,为什么不检查'admin'和'user'?
我假设您希望动态地向下拉列表中添加新条目,这将需要compareWith指令。请参阅此链接以获取一个简单示例 - https://netbasal.com/understanding-the-comparefn-input-in-angular-v4-4a401ef4fc4c
话虽如此,我认为您的比较方法应如下 -
roles = {
{id:admin, value:false},
{id:user, value:true}
}
public compareRoles(c1: any, c2: any): boolean {
return c1.value == c2.value;
}