chamrith
chamrith

Reputation: 27

How to change the background color of table row based on value in table cell?

I am using Angular *ngFor directive to generate a dynamic table. Here is the structure below:

       <tr *ngFor = 'let element of ph'>
            <td>{{element.timestamp}}</td>
            <td>{{element.ph}}</td>                   
       </tr>

The example image of the generated table is displayed below. Image Example

I want to color entire table rows containing 20 < PH Value < 50. How can I do it?

Upvotes: 0

Views: 7335

Answers (3)

SiddAjmera
SiddAjmera

Reputation: 39482

You could use [ngClass] and apply a class if the values are what you want them to be.

Here, use this:

<table border="1">
  <thead>
    <td>Reading Time</td>
    <td>PH</td>
  </thead>
  <tbody>
    <tr *ngFor='let element of ph'
      [ngClass]="{'color': (element.ph > 20 && element.ph < 50)}">
      <td>{{element.timestamp}}</td>
      <td>{{element.ph}}</td>
    </tr>
  </tbody>
</table>

Alternatively, as suggested by Yoel Rodriguez, you could also use [class.color] to apply it dynamically:

<table border="1">
  <thead>
    <td>Reading Time</td>
    <td>PH</td>
  </thead>
  <tbody>
    <tr *ngFor='let element of ph'
      [class.color]='element.ph > 20 && element.ph < 50'>
      <td>{{element.timestamp}}</td>
      <td>{{element.ph}}</td>
    </tr>
  </tbody>
</table>

And here's the color css class:

.color {
  color: white;
  font-weight: bold;
  background-color: red;
}

Sample StackBlitz

PS: I'm not suggesting the [ngStyle] approach as writing inline styles is not really a good practice.

Upvotes: 3

Nino Filiu
Nino Filiu

Reputation: 18551

You can use [ngClass], but [ngStyle] is more fit for small style changes:

<div [ngStyle]="{<property>: <value>}">

And for your particular case:

<tr [ngStyle]="{'background-color': (20<ph && ph<50) ? 'red' : 'white'}">

Upvotes: 1

alokstar
alokstar

Reputation: 499

You can simply use NgClass directive on your ph column. something like:

<td [ngClass]="{'first': true, 'second': true, 'third': false}">{{element.ph}}</td>

In other words, use particular class with particular styles if your condition is true.

Hope it helps!

Upvotes: 0

Related Questions