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

Angular动态加载mat-table显示表头但不展示行数据如何解决

问题原因

你当前的实现存在两个核心错误导致数据无法正常渲染:

  1. 数据源赋值逻辑错误:你直接用接口返回的普通数组覆盖了原本的MatTableDataSource实例,MatTableDataSource需要通过修改其内部的data属性来更新数据源,而非替换整个实例。
  2. 动态列的指令绑定不规范:使用插值语法给matColumnDef传值可能导致列标识匹配失败,无法正确映射单元格内容。

修复步骤

1. 修正数据源赋值逻辑

Store中的初始化代码无需修改:

public dataSource = new MatTableDataSource<any>([]);

其他文件中更新数据源的代码修改为:

// 原错误写法:this.store.dataSource = data;
// 修改为给MatTableDataSource的data属性赋值
this.store.dataSource.data = data;

2. 修正模板动态列绑定

将matColumnDef的插值写法改为属性绑定:

<mat-table mat-table [dataSource]="dataSource">
    <!-- 把 matColumnDef="{{col}}" 改为 [matColumnDef]="col" -->
    <ng-container *ngFor="let col of dispColumns" [matColumnDef]="col">
        <mat-header-cell *matHeaderCellDef>{{col}}</mat-header-cell>
        <mat-cell *matCellDef="let element ">
            {{element[col]}}
        </mat-cell>
    </ng-container>

    <mat-header-row *matHeaderRowDef="dispColumns"></mat-header-row>
    <mat-row *matRowDef="let row; columns: dispColumns;"></mat-row>
</mat-table>
<mat-paginator [pageSizeOptions]="[10, 25, 50, 100]" showFirstLastButtons
   aria-label="Select page of query data">
</mat-paginator>

3. 可选检查项

如果完成上述操作后仍有问题,检查以下配置:

  • 确认dispColumns数组中的列名,与数据源单条对象的属性名拼写、大小写完全一致,例如列名配置为userName时,数据源对象不能使用username作为属性名。
  • 如需使用分页功能,需要在组件中绑定分页器实例:
import { ViewChild, AfterViewInit } from '@angular/core';
import { MatPaginator } from '@angular/material/paginator';

export class Component implements OnInit, AfterViewInit {
  @ViewChild(MatPaginator) paginator!: MatPaginator;

  constructor(
    private store: Store,
  ) { }

  ngOnInit(): void {
  }

  ngAfterViewInit() {
    this.dataSource.paginator = this.paginator;
  }

  get dataSource() {
    return this.store.dataSource;
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 18:15:03