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

如何为Angular Material数据表格添加边框和表头行背景色

Angular Material 数据表格添加边框与表头背景色实现方法

现有代码

你当前使用的Angular Material表格模板代码如下:

<div class="example-container mat-elevation-z8">

  <mat-table [dataSource]="dataSource" matSort>

    <!-- Date Column -->
    <ng-container matColumnDef="Date">
      <mat-header-cell *matHeaderCellDef mat-sort-header> Date </mat-header-cell>
      <mat-cell *matCellDef="let row"> {{row.date}} </mat-cell>
    </ng-container>

    <!-- Name Column -->
    <ng-container matColumnDef="name">
      <mat-header-cell *matHeaderCellDef mat-sort-header> Name </mat-header-cell>
      <mat-cell *matCellDef="let row"> {{row.name}} </mat-cell>
    </ng-container>

    <!-- Download Column -->
    <ng-container matColumnDef="Download">
      <mat-header-cell *matHeaderCellDef mat-sort-header> Download </mat-header-cell>
      <mat-cell *matCellDef="let row" [style.color]="row.color"> {{row.download}} </mat-cell>
    </ng-container>

    <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
    <mat-row *matRowDef="let row; columns: displayedColumns;">
    </mat-row>
  </mat-table>

  <mat-paginator [pageSizeOptions]="[5, 10, 25, 100]"></mat-paginator>
</div>

当前运行效果:
当前表格效果
目标实现效果:
目标表格效果

具体实现方案

你不需要修改现有HTML代码,只需添加对应的CSS样式即可,分两种实现方式:

方式1:组件局部样式(推荐)

打开该组件对应的.css(或.scss/.less)样式文件,粘贴以下代码:

/* 表格外层容器添加边框 */
.example-container {
  border: 1px solid #e2e2e2;
  border-radius: 4px;
  overflow: hidden;
}

/* 设置表头行背景色,可自行替换颜色值 */
mat-header-row {
  background-color: #f5f5f5;
}

/* 表头单元格添加边框 */
mat-header-cell {
  border-right: 1px solid #e2e2e2;
  border-bottom: 1px solid #e2e2e2;
}
mat-header-cell:last-of-type {
  border-right: none;
}

/* 普通单元格添加边框 */
mat-cell {
  border-right: 1px solid #e2e2e2;
  border-bottom: 1px solid #e2e2e2;
}
mat-cell:last-of-type {
  border-right: none;
}
mat-row:last-of-type mat-cell {
  border-bottom: none;
}

如果添加后样式不生效,是Angular视图封装导致的,有两种解决方法:

  • 在样式选择器前加::ng-deep,例如::ng-deep mat-header-row
  • 或者在组件的@Component装饰器中添加配置encapsulation: ViewEncapsulation.None(需要先从@angular/core导入ViewEncapsulation)

方式2:全局样式

直接把上述CSS代码粘贴到项目全局的styles.css文件中,即可直接生效。

你可以根据需求自行修改边框颜色、粗细、表头背景色的数值,实现自定义效果。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 03:24:03