Home > Net >  How to put condition on table row color by the table data?
How to put condition on table row color by the table data?

Time:03-03

I am creating a table from two arrays using ngFor

    <tr *ngFor="let e of lis1; let k=index">
        <td>{{e}}  </td>
        <td>{{lis2[k]}}</td>
    
    </tr>

and the table created is something like this

Name  Age
a     15
b     20
c     25

I want to change the color of the row which has an age greater than 20. How to put this condition?? I am using angular typescript.

in lis1 I have an array of names(a,b,c) andin lis2 I have an array of age(15,20,25)

CodePudding user response:

There are different ways you can add styles to your element conditionally, ngStyle, ngClass, directly with attributes, etc.

I'll show You how to add styles using ngClass. You can simply check if the age is greater than 20 in [ngClass] to apply the class otherwise not.

<tr *ngFor="let e of lis1; let k=index" [ngClass]="{'background-red': lis2[k] > 20}">
     <td>{{e}}  </td>
     <td>{{lis2[k]}}</td>  
</tr>

In your CSS component simple add the class

.background-red{
     background-color: red;
}
  • Related