向 Angular material 数据表添加边框和 header 行背景色

Add border and header row background color to Angular material datatable

我需要为我的 Angular 数据 table 添加 table 边框和 header row 背景颜色。我在下面解释我的代码。

<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>

上面的代码生成如下输出。

但这里我需要完整的 table 边框,还需要 the first row background color 使用 CSS 到此 Angular material datatable,如下所示。

像上图一样,我需要添加边框和 header 行背景颜色。由于我没有 CSS 方面的经验,有人可以帮助解决这个问题吗?

样式有 2 个问题material:

  • 我们不能在不使用 ::ng-deep 的情况下在组件内部覆盖它们,后者已被弃用
  • 每个html标签里面都有很多由material生成的模板

但这是可能的,虽然很麻烦。

如果要更改 header 行的背景颜色,请添加:

.mat-header-row::ng-deep {
  background-color: black;
}

给你的 css.

如果要给 table 添加边框,请添加:

.mat-table::ng-deep {
  border: 1px solid red;
}

您只需要根据自己的喜好调整颜色 :)

不使用 depracated ::ng-deep 的第二种解决方案是将样式添加到全局 style.css 而不是组件,那么您只需要添加:

.mat-header-row
{
  background-color: black;
}
.mat-table {
  border: 1px solid red;
}