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

Angular中如何从数组生成带子列的表头表格

Angular 实现带双列子表头的表格结构

问题分析

你当前的代码在第二行表头中,先一次性渲染所有col1再渲染所有col2,导致子列顺序错乱(呈现1,1,1,2,2,2的排列),但正确结构应该是每个主列(A/B/C)下方对应自身的col1和col2(即1,2,1,2,1,2的顺序)。

修正后的实现方案

数组数据(无需修改)

headerRows = [
    {
        id: 1,
        column: 'A',
        col1: 1,
        col2: 2,
    },
    {
        id: 2,
        column: 'B',
        col1: 1,
        col2: 2,
    },
    {
        id: 3,
        column: 'C',
        col1: 1,
        col2: 2,
    },
];

HTML 模板(核心修改)

<table border="1" cellpadding="8">
    <thead class="thead">
        <tr>
            <th class="text" rowspan="2">Text</th>
            <!-- 主表头:每个列占2个子列宽度 -->
            <th *ngFor="let headerCell of headerRows" colspan="2">{{headerCell.column}}</th>
        </tr>
        <tr>
            <!-- 子表头:遍历每个主列,依次输出对应的col1和col2 -->
            <ng-container *ngFor="let cell of headerRows">
                <th>{{cell.col1}}</th>
                <th>{{cell.col2}}</th>
            </ng-container>
        </tr>
    </thead>
    <!-- 示例内容行 -->
    <tbody>
        <tr>
            <td>内容行</td>
            <td>数据1</td>
            <td>数据2</td>
            <td>数据3</td>
            <td>数据4</td>
            <td>数据5</td>
            <td>数据6</td>
        </tr>
    </tbody>
</table>

关键修改说明

  • 使用<ng-container>作为循环容器(不会生成额外DOM元素),遍历每个headerRow时连续输出该列对应的col1和col2表头单元格,确保子列与主列一一对应。
  • 表格的border和cellpadding是为了直观展示结构,可根据实际需求调整样式。

内容的提问来源于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 17:52:14