You need to enable JavaScript to run this app. Angular 11中如何将对象数组与表格tr、td实现数据绑定
优惠活动
大模型
产品
解决方案
定价
更多

Angular 11中如何将对象数组与表格tr、td实现数据绑定

问题根因

你遇到的报错Error trying to diff '[object Object]'. Only arrays and iterables are allowed核心原因是*ngFor指令仅支持遍历数组/可迭代对象,你现有代码中两层循环的遍历对象存在非数组类型:

  • 要么是你赋值给BitData的API返回结果本身不是数组
  • 要么是第一层循环拿到的每一个Item是普通对象,不是数组,导致第二层*ngFor="let dataItem of Item;"遍历失败
    另外你现有模板代码里多了一个多余的</div>闭合标签,也会触发模板渲染异常。

修复步骤

  1. 先确认API返回的数据结构,保证你赋值给BitData的是数组类型,每一个数组元素对应你要渲染的一行(即你说的Table1对应第一行元素,Table2对应第二行元素)
  2. 找到第一层Item里存储子表格数据的数组字段,把第二层循环的遍历对象替换成该字段即可

修复后示例代码

<table class="table align-items-center table-dark table-flush">
  <tbody>
    <!-- 第一层循环遍历BitData数组,每个Item对应一行 -->
    <tr class="col-sm-12 col-md-12 col-lg-12 col-xl-12" *ngFor="let Item of BitData;">
      <!-- 第二层循环遍历Item下的子数组,把itemList替换成你实际的子数据字段名 -->
      <td class="pad1" *ngFor="let dataItem of Item.itemList;">
        <div class="media align-items-center">
          <div class="col-sm-12 col-md-12 col-lg-12 col-xl-12 pad1">
            <div class="card card-stats mb-4 mb-xl-0 bg-gradient-info">
              <div class="card-body">
                <div class="row border">
                  <div
                    [ngClass]="dataItem.PLANNED_HOLE_SECTION == dataItem.ACTUAL_HOLE_SECTION ? 'col bg-gradient-success' : 'col bg-gradient-warning'">
                    <h5 class="h5 card-title text-white mb-0 font-sm">计划井段尺寸</h5>
                    <h5 class="h5 font-weight-bold font-md">{{dataItem.PLANNED_HOLE_SECTION}}</h5>
                  </div>
                  <div
                    [ngClass]="dataItem.PLANNED_HOLE_SECTION == dataItem.ACTUAL_HOLE_SECTION ? 'col bg-gradient-success' : 'col bg-gradient-warning'">
                    <h5 class="h5 card-title text-white mb-0 font-sm">实际井段尺寸</h5>
                    <h5 class="h5 font-weight-bold font-md">{{dataItem.ACTUAL_HOLE_SECTION}}</h5>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </td>
    </tr>
  </tbody>
</table>

调试技巧

可以在组件逻辑里打印数据确认结构,快速定位字段名:

// 拿到API返回后执行以下打印
console.log('BitData是否为数组:', Array.isArray(this.BitData));
if(this.BitData?.length) {
  console.log('第一个行数据的结构:', this.BitData[0]);
}

如果确实有遍历普通对象属性的需求,可以使用Angular自带的KeyValuePipe:

*ngFor="let attr of Item | keyvalue"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 17:15:04