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

Angular中基于多嵌套数组实现带rowspan的表格

实现多层嵌套数组的rowspan合并表格(Angular)

问题分析

你现有代码的核心问题:

  • [attr.rowspanspan] 是拼写错误,应为 [attr.rowspan]
  • 项目单元格的rowspan计算错误:应该是该项目下所有活动的总数量,而非组的数量
  • 表格结构错误:存在tr嵌套的情况,不符合HTML规范

解决方案

首先在组件中添加计算总活动数的方法,然后调整模板结构,让每个活动对应一行,项目和组的单元格通过rowspan跨对应行数,仅在对应分组的第一行渲染。

组件代码(app.component.ts)

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  data = [
    { id: 1, name: 'one', groups: 
    [{'name': 'gr1', campaigns :
     [{'name' : 'camp1'}, {'name' : 'camp2'}, {'name' : 'camp3'}]},
     {'name': 'gr2', campaigns :
      [{'name' : 'camp4'}, {'name' : 'camp5'}, {'name' : 'camp6'}]}
    ] },
    { id: 2, name: 'two', groups: [{'name': 'gr3', campaigns : [{'name' : 'camp7'}]}] },
    { id: 3, name: 'three', groups: [{'name': 'gr4', campaigns : [{'name' : 'camp8'}]}] },
    { id: 4, name: 'four', groups: [{'name': 'gr5', campaigns : [{'name' : 'camp9'}]}] }
  ];

  // 计算项目下的总活动数
  getTotalCampaigns(project: any): number {
    return project.groups.reduce((total: number, group: any) => total + group.campaigns.length, 0);
  }
}

模板代码(app.component.html)

<table class="table table-bordered table-hover" id="report">
  <!-- 表头 -->
  <tr>
    <th>Project</th>
    <th>Group</th>
    <th>Camps</th>
  </tr>

  <!-- 遍历项目 -->
  <ng-container *ngFor="let project of data">
    <!-- 遍历项目下的组 -->
    <ng-container *ngFor="let group of project.groups; let gIndex = index">
      <!-- 遍历组下的活动 -->
      <tr *ngFor="let campaign of group.campaigns; let cIndex = index">
        <!-- 仅在项目的第一个活动行渲染项目单元格,跨所有活动行 -->
        <td *ngIf="gIndex === 0 && cIndex === 0" [attr.rowspan]="getTotalCampaigns(project)">
          {{ project.name }}
        </td>
        <!-- 仅在组的第一个活动行渲染组单元格,跨该组所有活动行 -->
        <td *ngIf="cIndex === 0" [attr.rowspan]="group.campaigns.length">
          {{ group.name }}
        </td>
        <!-- 活动单元格,每行都渲染 -->
        <td>{{ campaign.name }}</td>
      </tr>
    </ng-container>
  </ng-container>
</table>

关键说明

  1. 项目单元格的rowspan:通过getTotalCampaigns计算该项目下所有活动的总数,确保单元格跨所有对应行
  2. 组单元格的rowspan:直接使用group.campaigns.length,确保单元格跨该组下的所有活动行
  3. 条件渲染:通过*ngIf="gIndex === 0 && cIndex === 0"确保项目单元格仅在该项目的第一个活动行显示;通过*ngIf="cIndex === 0"确保组单元格仅在该组的第一个活动行显示
  4. 结构规范:所有tr都是直接作为table或tbody的子元素,不存在嵌套,符合HTML表格规范

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 09:50:14