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

Angular 14:如何从JSON动态创建多个mat-table表格

实现步骤

1. 先处理数据格式

mat-table的dataSource需要接收数组格式的数据,但你JSON里的steps是单个键值对对象,得先把它转成[{key: 'i', value: '35%'}, {key: 'ii', value: '65%'}]这种数组结构,才能给表格用。在组件里加个转换函数就行:

// 组件类中的转换方法
transformSteps(steps: any[]): {key: string, value: string}[] {
  if (!steps || steps.length === 0) return [];
  // 取steps里的第一个对象(按你的示例结构)
  const stepObj = steps[0];
  // 把对象转成键值对数组
  return Object.entries(stepObj).map(([key, value]) => ({key, value}));
}

2. 模板里动态生成表格并绑定数据源

直接用*ngFor遍历你的JSON数组,每个循环项生成一个mat-table,同时把转换后的steps数组作为dataSource绑定进去。首行显示name的话,有两种方式:

方式一:用表头行合并列显示name

<div *ngFor="let item of jsonData" class="table-wrapper">
  <mat-table [dataSource]="transformSteps(item.steps)" class="mat-elevation-z8">
    <!-- 定义name列,合并两列显示 -->
    <ng-container matColumnDef="name">
      <mat-header-cell *matHeaderCellDef [attr.colspan]="2">{{ item.name }}</mat-header-cell>
    </ng-container>

    <!-- Key列 -->
    <ng-container matColumnDef="key">
      <mat-cell *matCellDef="let el">{{ el.key }}</mat-cell>
    </ng-container>

    <!-- Value列 -->
    <ng-container matColumnDef="value">
      <mat-cell *matCellDef="let el">{{ el.value }}</mat-cell>
    </ng-container>

    <!-- 渲染表头行(显示name) -->
    <mat-header-row *matHeaderRowDef="['name']"></mat-header-row>
    <!-- 渲染数据行 -->
    <mat-row *matRowDef="let row; columns: ['key', 'value']"></mat-row>
  </mat-table>
</div>

方式二:表格上方单独加标题行

如果觉得合并表头不够直观,也可以在每个表格上方直接放name作为标题:

<div *ngFor="let item of jsonData" class="table-wrapper">
  <h4>{{ item.name }}</h4>
  <mat-table [dataSource]="transformSteps(item.steps)" class="mat-elevation-z8">
    <!-- Key列(带表头) -->
    <ng-container matColumnDef="key">
      <mat-header-cell *matHeaderCellDef>项</mat-header-cell>
      <mat-cell *matCellDef="let el">{{ el.key }}</mat-cell>
    </ng-container>

    <!-- Value列(带表头) -->
    <ng-container matColumnDef="value">
      <mat-header-cell *matHeaderCellDef>百分比</mat-header-cell>
      <mat-cell *matCellDef="let el">{{ el.value }}</mat-cell>
    </ng-container>

    <mat-header-row *matHeaderRowDef="['key', 'value']"></mat-header-row>
    <mat-row *matRowDef="let row; columns: ['key', 'value']"></mat-row>
  </mat-table>
</div>

3. 必要的模块导入

别忘了在你的模块里导入Angular Material的表格相关模块,不然组件会报错:

import { MatTableModule } from '@angular/material/table';

@NgModule({
  imports: [
    // 其他模块
    MatTableModule
  ],
  declarations: [/* 你的组件 */]
})
export class YourFeatureModule { }

更优展示方案参考

如果之后允许调整展示逻辑,推荐这几种更合理的方式:

  • 单表格分组展示:用mat-table的分组功能,把相同name的项归到同一组里,不用生成N个独立表格,减少页面冗余。
  • 卡片式布局:每个JSON对象对应一个Material卡片,卡片头部显示name,内部用列表展示steps的键值对,比表格更轻量化。
  • 折叠面板:把每个对象的内容放进mat-expansion-panel,默认收起,点击展开查看详情,适合数据量较多的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 14:35:26