Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

enter image description here

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

How can we color individual cells in mat-table?

like image 777
Alexander Abakumov Avatar asked Oct 30 '17 21:10

Alexander Abakumov


1 Answers

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.

mat-row height

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.

mat-cell height

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.

like image 151
Romulo Avatar answered Sep 25 '22 00:09

Romulo