Angular Material表格:使用matColumnDef与*ngFor根据productTypeId展示产品分类及报错解决
问题分析与解决方案
你遇到的错误根源是重复生成了相同ID的列定义,Angular Material表格要求每个matColumnDef的ID必须唯一,而你的代码把*ngFor直接放在了matColumnDef所在的ng-container上,这会为每个productType条目创建一个ID为productTypeId的列——但你的表格displayedColumns数组里肯定只声明了一次productTypeId,表格找不到唯一匹配的列定义,就抛出了Could not find column with id "productTypeId"的错误。
而且从需求来看,你其实只需要一列来展示每个产品对应的分类名称,不需要为每个分类生成一列,所以原来的循环位置完全错了。下面是两种可行的解决方案:
方案一:用Map做映射(性能更优,推荐)
在组件类里先把产品类型数组转换成键值对映射,这样每次查找分类名称都是O(1)的时间复杂度,大数据量下更高效:
// 组件类中 productTypeMap: Map<number, string>; ngOnInit(): void { // 假设你的productType是格式为{id: number, name: string}的数组 this.productTypeMap = new Map( this.productType.map(type => [type.id, type.name]) ); }
然后在模板里直接通过Map获取对应名称:
<ng-container matColumnDef="productTypeId"> <th mat-header-cell *matHeaderCellDef mat-sort-header> Product Type </th> <td mat-cell *matCellDef="let row"> {{ productTypeMap.get(row.productTypeId) || 'Unknown' }} </td> </ng-container>
方案二:在单元格内使用find方法(小数据量可用)
如果你的产品类型数据量很小,可以直接在模板里用find方法匹配,省去转换Map的步骤:
<ng-container matColumnDef="productTypeId"> <th mat-header-cell *matHeaderCellDef mat-sort-header> Product Type </th> <td mat-cell *matCellDef="let row"> {{ productType.find(type => type.id === row.productTypeId)?.name || 'Unknown' }} </td> </ng-container>
最后别忘了确认你的displayedColumns数组里包含productTypeId,比如:
displayedColumns: string[] = ['其他列名', 'productTypeId', ...];
内容的提问来源于stack exchange,提问作者Chimer4.0
相关产品推荐
相关产品推荐

