【问题标题】:Add border and header row background color to Angular material datatable向 Angular 材质数据表添加边框和标题行背景颜色
【发布时间】:2021-09-02 13:48:08
【问题描述】:

我需要在我的 Angular 数据表中添加表格边框和 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>

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

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

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

【问题讨论】:

    标签: css angular angular-material


    【解决方案1】:

    样式材料有两个问题:

    • 如果不使用已弃用的 ::ng-deep,我们无法在组件内部覆盖它们
    • 每个html标签里面都有很多由material生成的模板

    但这是可能的,尽管很麻烦。

    如果你想改变标题行的背景颜色添加:

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

    到你的CSS。

    如果要为表格添加边框添加:

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

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

    不使用已弃用 ::ng-deep 的第二个解决方案是将样式添加到全局 style.css 而不是组件,然后您只需添加:

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

    【讨论】:

    • 好像没问题。我添加了.mat-table { overflow: auto; max-height: 500px; border: 1px solid black; } .mat-header-row{ background: #005173; },但标题字体颜色没有改变,也不可见。
    • 添加.mat-header-cell { color: red; }
    • 我使用的是.mat-header-row{ background: #005173; } .mat-header-cell { color: white; } ,但标题字体颜色没有反映。
    • 也许其他样式正在覆盖它? stackblitz.com/edit/angular-qvxmhe?file=src/app/… 在 stackblitz 上运行良好
    猜你喜欢
    • 1970-01-01
    • 2018-03-02
    • 2013-03-09
    • 2013-03-27
    • 2022-01-24
    • 2017-12-25
    • 1970-01-01
    • 1970-01-01
    • 2019-11-25
    相关资源
    最近更新 更多