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

Angular中如何在表格中展示对象数组?

解决Angular表格渲染cellContent数据的问题

问题分析

你的代码存在两个核心问题:

  1. 数据结构语法错误:cellContent中row1对象末尾缺少逗号,导致JavaScript无法正确解析该数组。
  2. 遍历逻辑错误:原HTML中使用group.item遍历,但你的数据结构里不存在item属性;同时Angular不能直接遍历对象属性,必须借助keyvalue管道转换为可遍历的键值对数组。

修复步骤

1. 修正数据结构语法

给row1对象末尾添加逗号,确保数据能正常解析:

cellContent = [
  {
    row1: {
      groupA: { col1: '100', col2: '100' },
      groupB: { col1: '100', col2: '100' },
      groupC: { col1: '100', col2: '100' },
      groupD: { col1: '100', col2: '100' },
      groupE: { col1: '100', col2: '100' },
      groupF: { col1: '100', col2: '100' },
      groupG: { col1: '3,900', col2: '3,900' },
    }, // 补上这个逗号
    row2: { /* 你的其他行数据 */ }
  }
];

2. 编写正确的HTML渲染代码

根据你的需求,提供两种实现方案:

方案一:渲染所有行(row1、row2等)

将每个row对应表格的一行,每个group的col1作为单元格:

<table>
  <!-- 遍历cellContent数组中的元素 -->
  <ng-container *ngFor="let content of cellContent">
    <!-- 遍历每个row(row1、row2) -->
    <tr *ngFor="let row of content | keyvalue">
      <!-- 遍历当前row下的所有group,渲染col1内容 -->
      <td *ngFor="let group of row.value | keyvalue">
        {{ group.value.col1 }}
      </td>
    </tr>
  </ng-container>
</table>
方案二:仅渲染指定行(比如row1)

如果只需要展示row1的内容:

<table>
  <tr>
    <!-- 直接遍历row1下的所有group -->
    <td *ngFor="let group of cellContent[0].row1 | keyvalue">
      {{ group.value.col1 }}
    </td>
  </tr>
</table>

关键说明

  • keyvalue管道是Angular内置工具,用于将对象转换为{key: string, value: any}格式的数组,让*ngFor可以遍历对象属性。
  • 遍历逻辑必须匹配数据的嵌套层级:cellContent数组 → 行对象(row1/row2) → 分组对象(groupA/groupB等) → col1属性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 06:03:12