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

Angular mat-table动态列绑定:如何在数据绑定中传入动态属性名?

基于JSON数据动态生成Angular mat-table常见问题解答

核心目标

基于JSON数据动态生成Angular mat-table表格

问题背景

已知columnsList为JSON数据所有属性名组成的数组,单条JSON示例结构如下:

{
  "planId":"abcd",
  "rateAreaId":"lmpo",
  "singleMonthly":0,
  "twoPeopleMonthly":0,
  "familyMonthly":0
}

问题1:如何分别实现遍历列名数组和数据源的两层循环逻辑?

  • 第一层遍历列名数组:你现有的写法思路正确,直接在<ng-container>上绑定*ngFor="let columnName of columnsList",配合matColumnDef属性即可动态生成所有列的定义,包含表头、单元格、页脚的基础结构。
  • 第二层遍历数据源:不需要手动编写循环逻辑,Angular Material的mat-table组件已经封装了该能力。你只需给<mat-table>的[dataSource]属性绑定你的数据源数组carrierRates,再配合<mat-row>的*matRowDef="let row; columns: columnsList;"声明,组件会自动遍历数据源的每一项,生成对应数据行。

问题2:如何将动态变量columnName作为属性名传入绑定语句,正确读取对应属性值?

你当前使用的{{itemRate.$columnName}}写法是错误的,JavaScript/TypeScript中要使用动态变量作为对象属性名,需要用方括号访问语法,直接修改为{{itemRate[columnName]}}即可正确读取对应属性的值。

修正后的完整模板代码

<mat-table class="mat-elevation-z8" *ngIf="carrierRates" [dataSource]="carrierRates">
  <!-- 动态生成所有列定义 -->
  <ng-container *ngFor="let columnName of columnsList" [matColumnDef]="columnName">
    <mat-header-cell *matHeaderCellDef>{{columnName}}</mat-header-cell>
    <mat-cell *matCellDef="let itemRate">
      {{itemRate[columnName]}}
    </mat-cell>
    <mat-footer-cell *matFooterCellDef></mat-footer-cell>
  </ng-container>

  <mat-header-row *matHeaderRowDef="columnsList"></mat-header-row>
  <mat-row *matRowDef="let row; columns: columnsList;"></mat-row>
  <mat-footer-row *matFooterRowDef="columnsList"></mat-footer-row>
</mat-table>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 12:24:08