How set css to alternating rows in angular 4

3.6k Views Asked by At

I would like to define a class to alternating rows in angular 4, how to do this?

HTML

 <div class="scrollbars">
            <div  *ngFor="let path of Xyzpaths">
                    <div>{{path.xyz}}</div>
                    <div>{{path.salesItem}}</div>
                    <div>{{path.path1}}</div>
                    <div>{{path.path2}}</div>
            </div>
   </div>

CSS

.odd  {   background-color: #f2f9ff;} 
.even {   background-color: #eceff3; }
2

There are 2 best solutions below

1
On BEST ANSWER

yes, you can use the odd and even local variables in the ngFor, something like this:

<div class="scrollbars">
    <div *ngFor="let path of Xyzpaths index as i; let even = even; let odd = odd" 
     [ngClass]="{ myOddClass: odd, myEvenClass: even }">
        <div>{{path.xyz}}</div>
        <div>{{path.salesItem}}</div>
        <div>{{path.path1}}</div>
        <div>{{path.path2}}</div>
    </div>
</div>

Documentation.

0
On

Use CSS's nth-child selector:

scrollbars > div:nth-child(even) {background-color: #f2f9ff;}
scrollbars > div:nth-child(odd) {background-color: #eceff3;}

Try to avoid adding template logic where you don't need to, and in this case, you don't need to -- CSS can do it all and is orders of magnitude more efficient than using a template directive.