Angular Mat-Table报错:找不到id为inchiKey的列 求助
报错根因
Angular Material Table 的列ID匹配规则为严格大小写敏感匹配,你的代码中列命名存在大小写不一致问题:
- 组件TS文件内
displayedColumns数组声明的首个列ID为inchiKey(字母K为大写) - 模板HTML中对应列容器的
matColumnDef属性值写为inchikey(字母k为小写)
框架渲染时会按照displayedColumns中声明的ID逐一匹配模板内带matColumnDef标识的列容器,大小写不匹配时就会抛出Could not find column with id "inchiKey"错误。
修复方法
保证TS中displayedColumns的列ID和模板中matColumnDef的取值完全一致即可,推荐统一和接口字段命名对齐,修改模板对应列定义:
<!-- 将原matColumnDef="inchikey"修改为大写K的版本 --> <ng-container matColumnDef="inchiKey"> <th mat-header-cell *matHeaderCellDef> inchiKey </th> <td mat-cell *matCellDef="let element"> {{element.inchiKey}} </td> </ng-container>
如果不想改模板,也可以把TS中displayedColumns的首个元素值改为全小写的'inchikey',但这种写法和接口字段的驼峰命名不统一,后续维护易出问题,不推荐使用。
额外优化建议
修复列匹配问题后如果存在渲染异常,可以补充两点校验:
- 确认
MatTableModule已经在当前组件所属的特性模块或共享模块中正确导入 - 当前代码给
MatTableDataSource传值时取的是res[0],需确认该值为数组类型,如果后端返回的res[0]是单条数据对象而非数组,会导致表格行渲染失败,可以在赋值时增加类型兜底:
getdatabyMol() { this.rs.getoutputMol().subscribe({ next: (res:any) => { const rawData = Array.isArray(res[0]) ? res[0] : [res[0]]; this.dataSource = new MatTableDataSource<outputMol>(rawData); }, error: (e) => console.log("No data found" + e), complete: () => this.onLoading = false }) }
内容的提问来源于stack exchange,提问作者María
相关产品推荐
相关产品推荐

