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>
关键说明
- 项目单元格的rowspan:通过
getTotalCampaigns计算该项目下所有活动的总数,确保单元格跨所有对应行 - 组单元格的rowspan:直接使用
group.campaigns.length,确保单元格跨该组下的所有活动行 - 条件渲染:通过
*ngIf="gIndex === 0 && cIndex === 0"确保项目单元格仅在该项目的第一个活动行显示;通过*ngIf="cIndex === 0"确保组单元格仅在该组的第一个活动行显示 - 结构规范:所有
tr都是直接作为table或tbody的子元素,不存在嵌套,符合HTML表格规范
内容的提问来源于stack exchange,提问作者Abdul Chamarak
相关产品推荐
相关产品推荐

