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

Angular中如何避免二维数组通过ngFor渲染元素时重复显示?

Angular嵌套数组渲染表格去重解决方案

问题场景

我有一个嵌套二维字符串数组,希望将每个内层数组的内容渲染为一个表格:第一个表格展示第一个索引的数组值,第二个表格展示第二个索引的数组值。

当前使用的Angular模板代码:

<ng-container *ngFor="let h of headers; let h = index">
   <ng-container *ngFor = "let rows of test; let i = index">
      <ng-container *ngFor = "let row of rows; let j = index">
         <label *ngIf="h===i">
            {{row}}
         </label>
      </ng-container>
   </ng-container>
</ng-container>

.ts文件中的数据定义:

headers = ['Header1', 'Header2']
test = [['Test1', 'Test2'], ['Test3', 'Test4', 'Test5']]

当前问题:渲染结果中表格内的元素重复显示——第一个表格两次出现Test1和Test2,第二个表格两次出现Test3、Test4、Test5;期望每个表格仅显示对应内层数组的元素一次。

问题原因

三层嵌套循环导致重复遍历:外层遍历headers的每个元素时,都会完整遍历一遍test数组,再通过h===i过滤匹配项。因为headers有2个元素,所以每个test子数组会被遍历2次,最终元素重复渲染。

解决方案

只需要一层循环关联headers和test的对应索引,直接遍历目标子数组即可,无需多层嵌套:

修改后的模板代码

<ng-container *ngFor="let header of headers; let idx = index">
  <!-- 表格标题 -->
  <h3>{{header}}</h3>
  <!-- 渲染对应索引的test子数组为表格 -->
  <table border="1">
    <tbody>
      <tr>
        <td *ngFor="let item of test[idx]">{{item}}</td>
      </tr>
    </tbody>
  </table>
</ng-container>

无headers的简化写法

如果不需要依赖headers数组,也可以直接遍历test数组:

<ng-container *ngFor="let group of test; let idx = index">
  <h3>Header{{idx + 1}}</h3>
  <table border="1">
    <tbody>
      <tr>
        <td *ngFor="let item of group">{{item}}</td>
      </tr>
    </tbody>
  </table>
</ng-container>

修改后每个test子数组只会被遍历一次,对应生成一个表格,不会出现重复渲染的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 12:55:26