angular - 如何在 mat-select 中设置模型?
问题描述
我有多个mat-select元素:
<mat-select [formControl]="dropDownControl" multiple></mat-select>
它按类型包含选项元素:
export interface Employee {
name: string;
login: string;
}
我尝试使用以下方法选择选项:
ngOnInit() {
this.dropDownControl.setValue([
{ name: 'aaaa', login: 'aaa_login' },
{ name: 'bbb', login: 'bbb_login' },
]);
}
但是选择列表中的选项元素没有被选中(选中),为什么?
解决方案
使用选项值作为对象时。我们必须使用自定义比较功能来跟踪对象身份。将compareWith与 mat-select 一起使用。
与之比较
将选项值与选定值进行比较的函数。如果它返回 true,则该值将在复选框中被选中。
组件.html
<mat-form-field>
<mat-select [compareWith]="compareWith" [formControl]="dropDownControl" placeholder="Favorite food" multiple>
<mat-option *ngFor="let item of items" [value]="item">
{{item.login}}
</mat-option>
</mat-select>
</mat-form-field>
组件.ts
compareWith(obj1,obj2){
return obj1 && obj2 && (obj1.login === obj2.login || obj1.name === obj2.name);
}
推荐阅读
- javascript - 在 Jest 测试中触发 useEffect
- database - dynamodb 中的建议引擎 - 查询与不同记录无关的记录
- python - AppScreener 说我的 SQL 代码有一些 SQL Injection 漏洞
- c++ - C++ 优雅的数组切片
- subscription - 无法续订 RHEL 7.6 开发人员帐户订阅
- javascript - 为什么我得到,无法设置未定义的属性
- java - HL7 中的“重复”、“组件”和“子组件”是什么意思?
- php - 调用数组上的成员函数 - 未捕获的错误
- react-native - 如何更改占位符颜色 React Native RNPickerSelect
- powershell - Powershell仅在使用参数而不是使用选择时返回结果