使用mat-optgroup时compareWith函数x2参数为undefined问题咨询
问题原因
- 使用
mat-optgroup时,Angular Material的compareWith函数不仅会对比mat-option的value值,还会先遍历所有mat-optgroup节点尝试对比分组的value属性。你的代码未给mat-optgroup设置value,因此这一轮对比时第二个参数x2会是undefined。 - 若
productGroups为异步加载的数据,初始渲染时mat-option还未生成,也会导致首次执行compareWith时找不到对应的选项值,x2为undefined。
修复方案
1. 给mat-optgroup绑定value属性
给每个mat-optgroup绑定唯一的value值,避免分组对比时拿到undefined,修改后的模板代码如下:
<mat-form-field> <mat-label>Products</mat-label> <mat-select [compareWith]="compareWith"> <mat-optgroup *ngFor="let group of productGroups" [label]="group.name" [value]="group.id" > <mat-option *ngFor="let item of group.Items" [value]="item"> {{ item.productName}} </mat-option> </mat-optgroup> </mat-select> </mat-form-field>
2. 给compareWith添加空值校验
不管是否使用分组,都建议给对比函数增加边界判断,避免空值报错,修改后的函数代码如下:
compareWith(x1: any, x2: any): boolean { console.log('compareWith', x1, x2); return x1 && x2 ? x1.id === x2.id : x1 === x2; }
3. 异步数据场景优化
如果productGroups是从接口异步获取的,建议等分组数据加载完成后再给mat-select绑定的ngModel赋值,避免初始渲染时找不到对应选项。
内容的提问来源于stack exchange,提问作者Neptulon
相关产品推荐
相关产品推荐

