Search code examples
cssangular6

Change color of text in td based on value in Angular 6


I have a status column in my table where I need to show different color text based on value. I am working using Angular 6.

<table>
<th>Status</th>
<th>Name</th>
<tr *ngFor="let data of data >
<td>{{data.status}}</td>
<td>{{data.name}}</td>
</tr>
</table>

If the status is Pass and Approved, then the text is in green color, If the status is failed and Error, then the text is in red color, If the status is a warning, then the text is in yellow color, If the status is Ignored, then the text is in blue color,

Can anyone please help me how to do this in Angular 6.


Solution

  • First, you can instantiate an array for corresponding colors:

    Typescript:

    colors = [{ status: "Passed", color: "red" }, { status: "Approuved", color: "red" }, 
                    { status: "warning", color: "green" }, { status: "Ignored", color: "yellow" }]
    

    Then you can use ngStyle to set the style dynamically:

    HTML

    ...
    <tr *ngFor="let row of data" [ngStyle]="{'background':getColor(row.status)}">
    ...
    </tr>
    

    were getColor is the following method:

    Typescript

    getTheColor(status) {
           return this.colors.filter(item => item.status === status)[0].color 
           // could be better written, but you get the idea
    }
    

    It return the color value based on status from the corresponding color array

    That's it

    Demo