chamrith
chamrith

Reputation: 27

How to add a background color to table row based on data in table cell?

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

         <tr class="tr1" *ngFor="let participant of allParticipants">

            <td class="participant-properties">{{participant.stakeholderId}}</td>

            <td class="participant-properties">{{participant.name}}</td>

            <td class="participant-properties">{{participant.rating}}</td>

         </tr>

enter image description here

Above table load when I go to that specific page. Above mentioned tr, last table data (td) has there values for rating:active .rejected and warn. I want to color the entire table row which has the value active in green, warn in yellow and rejected in red at the time of display it.

Upvotes: 2

Views: 1608

Answers (3)

Fullstack Guy
Fullstack Guy

Reputation: 16908

You can use [ngStyle] to bind to a method which would return the appropriate color.

In the template add the [ngStyle] to the <tr>:

<tr class="tr1" *ngFor="let participant of allParticipants" [ngStyle]="getBgColor(participant.rating)">

    <td class="participant-properties">{{participant.stakeholderId}}</td>

    <td class="participant-properties">{{participant.name}}</td>

    <td class="participant-properties">{{participant.rating}}</td>

</tr>

In the controller you can use a switch case or a Map to check the condition and return the appropriate style as an Object to the [ngStyle] binding in the template.

getBgColor(rating: string){
    switch(rating)
    {
      case'active':
       return {'background':'#b3ffcc'};
      case 'warn':
       return {'background':'#ffffb3'};
      case 'rejected':
       return {'background':'#ffb3b3'};
    }
 }

Here is a stackblitz demo: https://stackblitz.com/edit/angular-4gb9vh

Upvotes: 0

user184994
user184994

Reputation: 18281

You can create a class for each style, like so:

tr.active td {
  background-color: #ddffdd;
}

tr.warn td {
  background-color: #ffffbb;
}

tr.rejected td {
  background-color: #ffdddd;
}

table {
  border-collapse: collapse;
  border-spacing: 0;
}

td {
  padding: 3px;
}

And then apply the class using ngClass, like so:

<tr class="tr1" *ngFor="let participant of allParticipants" [ngClass]="participant.rating">

Here is a Stackblitz example

Upvotes: 4

Steve Kirsch
Steve Kirsch

Reputation: 185

this should work for you:

$("table tr").find('td:last').each(function(){
    let td = $(this);
    let text = td.text();
    let color = 'white';
    switch (text) {
        case 'rejected': color = 'red'; break;
        case 'warn': color = 'orange'; break;
        case 'active': color = 'green'; break;
    }

    td.css('backgroundColor', color);
});

Upvotes: 0

Related Questions