You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 5中Mat-table仅显示行不渲染数据的问题排查求助

嘿,我之前也碰到过类似的mat-table不渲染数据的问题,结合你说的情况(ngFor正常、控制台无错、能显示空行),大概率是这几个地方出问题了,咱们一个个排查:

可能的原因及解决方案

1. 数据源绑定未正确处理Observable

如果你的组件变量是Observable类型(比如data$: Observable<YourDataType[]>),直接绑给[dataSource]是不行的——mat-table不会自动订阅Observable。这时候有两种处理方式:

  • 模板里用async管道自动订阅(推荐,不用手动管理订阅):
    <table mat-table [dataSource]="yourObservableData | async">
      <!-- 列定义内容 -->
    </table>
    
  • 或者在组件里手动订阅,把数据赋值给普通数组:
    dataList: YourDataType[] = [];
    
    ngOnInit() {
      this.notificationService.getData().subscribe(data => {
        this.dataList = data;
        // 要是担心变更检测没触发,可以加这句(不过ngFor正常的话大概率不需要)
        // this.cdr.detectChanges();
      });
    }
    
    然后模板绑定[dataSource]="dataList"

2. 列定义与模板的mat-cell不匹配

这是最容易踩的坑!比如你在matColumnDef里定义的是'notificationId',但在mat-cell里写的是{{element.id}},或者列名拼写错误(大小写、多字少字),都会导致数据渲染不出来。举个正确的对应例子:

<!-- 列定义 -->
<ng-container matColumnDef="notificationId">
  <th mat-header-cell *matHeaderCellDef> 通知ID </th>
  <td mat-cell *matCellDef="let element"> {{element.notificationId}} </td>
</ng-container>

<!-- 表头和行要对应列数组 -->
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>

一定要确保displayedColumns数组里的每一项,和matColumnDef的名称、element.xxx的属性名完全一致(包括大小写)!

3. 使用MatTableDataSource时未正确赋值

如果你用了MatTableDataSource来包装数据,不能直接把Observable赋值给它,得先拿到数组数据再赋值给data属性:

dataSource = new MatTableDataSource<YourDataType>();

ngOnInit() {
  this.notificationService.getData().subscribe(data => {
    this.dataSource.data = data;
  });
}

然后模板绑定[dataSource]="dataSource"

4. 数据结构不匹配

比如你的服务返回的是嵌套对象(比如{ code: 200, data: [...] }),但你直接把整个响应对象绑给了dataSource,这时候mat-table会把整个对象当成一行数据,自然渲染不出内容。这时候要先提取出数组部分:

// 假设服务返回的是这种嵌套结构
this.notificationService.getData().subscribe(response => {
  this.dataList = response.data; // 只取数组部分赋值
});

内容的提问来源于stack exchange,提问作者umutesen

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 10:00:55