You need to enable JavaScript to run this app. Angular使用mat-table报错找不到id为MDesc的列如何解决?
优惠活动
大模型
产品
解决方案
定价
更多

Angular使用mat-table报错找不到id为MDesc的列如何解决?

问题排查与解决方案

1. 核心错误:缺少mat-table必要配置项

你当前的HTML代码缺失两个mat-table必须的配置,是触发列找不到报错的直接原因:

  • 未在table标签上绑定列配置数组
  • 未定义表头行、数据行的渲染模板

修改后的完整table头部和尾部代码如下:

<!-- 头部添加[displayedColumns]绑定 -->
<table mat-table [dataSource]="list_models" [displayedColumns]="displayedColumnsModel" matSort style="width: 100%;"> 
  <!-- 原有列定义代码保持不变 -->
  <ng-container matColumnDef="id">...</ng-container>
  <ng-container matColumnDef="description">...</ng-container>
  <ng-container matColumnDef="MDesc">...</ng-container>
  <ng-container matColumnDef="BDesc">...</ng-container>

  <!-- 所有列定义结束后补充行渲染配置 -->
  <tr mat-header-row *matHeaderRowDef="displayedColumnsModel"></tr>
  <tr mat-row *matRowDef="let row; columns: displayedColumnsModel;"></tr>
</table>

2. 次要错误:displayedColumns包含未定义的列

你TS代码里的displayedColumnsModel数组包含了action字段,但是HTML中没有定义matColumnDef="action"的对应列,会触发额外的列缺失错误,按需二选一修复:

  • 不需要操作列:直接删除数组中的'action'项:
displayedColumnsModel: string[] = ['id','description','MDesc','BDesc'];
  • 需要操作列:在HTML列定义中补充action列的对应代码:
<ng-container matColumnDef="action">
  <th mat-header-cell *matHeaderCellDef style="text-align: center;">操作</th>
  <td mat-cell *matCellDef="let item" style="text-align: center;">
    <!-- 此处放置编辑、删除等操作按钮 -->
  </td>
</ng-container>

3. 兜底校验:确认后端返回字段大小写

部分数据库(如Linux环境下的MySQL)默认会将查询字段名转为小写,你可以在请求回调中打印返回值确认字段名是否和前端定义的MDesc、BDesc大小写一致:

get_data_Model(){
   this.http.get<any>("http://localhost:3000/listmodels").subscribe(
      res => {
        console.log('后端返回数据:', res) // 控制台查看返回对象的键名是否匹配
        this.list_models.data = res
      }
   );
}

如果存在大小写不一致问题,修改SQL给字段指定别名即可:

SELECT modeltbl.id, modeltbl.MDesc AS MDesc, brandtbl.BDesc AS BDesc, captiontbl.description 
FROM ((modeltbl INNER JOIN brandtbl ON modeltbl.brandcode = brandtbl.id) INNER JOIN captiontbl ON modeltbl.captioncode = captiontbl.id)

内容的提问来源于stack exchange,提问作者mahdi.gh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.21 03:36:03