简体   繁体   中英

Fill a mat-table's cell with a color

I have a fairly basic column in a mat-table as follows:

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

    <ng-container matColumnDef="zone">
        <mat-header-cell *matHeaderCellDef mat-sort-header></mat-header-cell>
        <mat-cell *matCellDef="let item" [style.background-color]="'#' + item.zone.color"></mat-cell>
    </ng-container>

    ...

</mat-table>

I'd like to fill zone column cells with some colors varying from row to row (not the whole row, only cells of this specific column).

All I could find so far is coloring the whole row.

The cells of the zone column are rendered to the following HTML:

<mat-cell class="mat-cell cdk-column-zone mat-column-zone" role="gridcell" style="background-color: rgb(255, 182, 193);" _ngcontent-c8=""></mat-cell>

We can see that background-color style property has been correctly applied, but the problem is that cell's height is 0. because the cell doesn't have any content. I tried to put an &nbsp; inside the cell, but it gets displayed as a thin bar with top and bottom margins:

在此输入图像描述

And what I want is to color the whole cell including its margins.

How can we color individual cells in mat-table ?

If you look at the default CSS provided by Angular Material , you will notice that the mat-row element has a minimum height of 48px .

垫排高度

But if you look at the mat-cell you will notice that it don't have a minimum neither a default height set, it relies on the parent element (the row) display / alignment properties to stay centered.

垫子高度

If you look at the previous image it shows exactly the area that is being colored by the background color property in your code.

So for changing the background color for the entire cell, one of your options would be to set the same minimum height used by the rows to the cells, which could be done using the following CSS declaration:

.mat-cell, .mat-header-cell {
    flex: 1;
    min-height: 48px;
    display: flex;
    align-items: center;
}

And then simple use the background color property for changing the color.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM