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

Angular Mat-Table表头行跨行设置问题:如何让指定列跨多行表头并移除多余列

解决Mat Table多行表头中行跨行及多余列问题

我之前也碰到过一模一样的问题,核心就是要让跨行的表头单元格占据多行空间,同时避免后续表头行重复渲染该列。下面是具体的解决步骤和代码示例:

关键思路

多余的“Cost”列是因为每一行表头都会按完整列数组渲染所有列,所以我们需要:

  1. 给目标表头单元格设置rowspan属性,让它跨越多行
  2. 为后续的表头行单独定义不包含该列的列数组,避免重复渲染

具体实现

1. 定义列数组(TS代码)

在组件类中,我们需要定义两套列数组:一套用于完整的第一行表头,一套用于后续表头行(去掉需要跨行的“cost”列):

import { Component } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';

interface Product {
  product: string;
  category: string;
  price: number;
  cost: number;
}

@Component({
  selector: 'app-table',
  templateUrl: './table.component.html',
  styleUrls: ['./table.component.css']
})
export class TableComponent {
  dataSource = new MatTableDataSource<Product>([
    {product: 'Laptop', category: 'Electronics', price: 999, cost: 600},
    {product: 'Shirt', category: 'Apparel', price: 29, cost: 10},
  ]);

  // 第一行表头的完整列
  displayedColumns: string[] = ['product', 'category', 'price', 'cost'];
  // 第二行表头的列(移除cost)
  secondHeaderColumns: string[] = ['product', 'category', 'price'];
}

2. 调整表头模板(HTML代码)

在模板中,给“Cost”的表头单元格添加rowspan="2"(假设是两行表头),然后用单独的列数组渲染第二行表头:

<table mat-table [dataSource]="dataSource" class="mat-elevation-z8">

  <!-- Product 列定义 -->
  <ng-container matColumnDef="product">
    <th mat-header-cell *matHeaderCellDef> Product </th>
    <td mat-cell *matCellDef="let element"> {{element.product}} </td>
  </ng-container>

  <!-- Category 列定义 -->
  <ng-container matColumnDef="category">
    <th mat-header-cell *matHeaderCellDef> Category </th>
    <td mat-cell *matCellDef="let element"> {{element.category}} </td>
  </ng-container>

  <!-- Price 列定义 -->
  <ng-container matColumnDef="price">
    <th mat-header-cell *matHeaderCellDef> Price </th>
    <td mat-cell *matCellDef="let element"> {{element.price}} </td>
  </ng-container>

  <!-- Cost 列定义:设置rowspan跨两行 -->
  <ng-container matColumnDef="cost">
    <th mat-header-cell *matHeaderCellDef rowspan="2" class="vertical-center"> Cost </th>
    <td mat-cell *matCellDef="let element"> {{element.cost}} </td>
  </ng-container>

  <!-- 第一行表头:使用完整列数组 -->
  <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>

  <!-- 第二行表头:使用移除cost的列数组 -->
  <tr mat-header-row *matHeaderRowDef="secondHeaderColumns"></tr>

  <!-- 数据行 -->
  <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>

3. 优化样式(CSS代码)

为了让跨行的表头文字垂直居中,添加以下样式:

.vertical-center {
  vertical-align: middle;
}

扩展说明

如果你的表头是三行或更多行,只需要:

  • 将rowspan的值设置为对应的行数(比如rowspan="3")
  • 所有后续的表头行都使用移除了“cost”列的数组渲染

这样就能完美实现“Cost”列跨多行表头,同时不会出现多余的重复列了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 21:57:46