Saif Ali
Saif Ali

Reputation: 547

How to style individual rows of Angular Material Data Table?

I want to style the individual rows of the data table based on some json values.

For example if a particular row has a temperature value of >30, I have to color that row as red. If it is between 30 to 50, the color should be green. Else the color should be green.

As of now I am only able to target the even rows or odd rows using:

tr:nth-child(even)/tr:nth-child(odd).

Upvotes: 4

Views: 5348

Answers (2)

codequiet
codequiet

Reputation: 1242

You should be able to add CSS classes directly to the row elements:

<tr mat-row *matRowDef="let row; columns: displayedColumns;"
    class="temperature-row"
    [ngClass]="{'high': row.temperature > 30}">
</tr>

Then you can use the classes to style the rows as desired:

.temperature-row {
    background-color: green;
}

.temperature-row.high {
    background-color: red;
}

Upvotes: 8

Maciejek
Maciejek

Reputation: 659

I like to style table rows using this pattern:

  <tr *ngFor="let temperature of temperatures"
                [ngClass]="{'green' : temperature.value == 10, 'orange' : temperature.value == 20, 'red' : temperature.value == 30}">
              <td>{{temperature.value}}</td>
  </tr>

And I define my colours, or any other styles, for those rows in CSS like this:

.red{
   color: red;
}
.orange{
    color: orange;
}
.green{
   color: green;
}

Upvotes: 1

Related Questions