如何转换以下对象(从我的端点检索)以初始化Angular Material 2,Multi-select表单字段:
来自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>
FormGroup:
createForm(): FormGroup
{
return this._formBuilder.group({
roles : [[this.roles]],
});
}
compareWith功能:
public compareRoles(c1: any, c2: any): boolean {
return c2[0].hasOwnProperty(c1) && c2[0][c1]
}
出于某种原因,我不断收到以下错误:
"Cannot read property 'hasOwnProperty' of undefined"
我错过了什么?我只是希望多选框能够预先填充来自API的数据。
如果你这样做
public compareRoles(c1: any, c2: any): boolean {
if (c2 && c2[0]) {
return c2[0].hasOwnProperty(c1) && c2[0][c1];
}
return false;
}
它应该使错误沉默。你可以在返回false之前添加一个debugger
语句来弄清楚为什么没有定义c2 [0](没有完整的工作演示,它有点难以诊断)。