3

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; }
free
  • 153
  • 1
  • 2
  • 18
  • Possible duplicate of [Using CSS :even and :odd pseudo-classes with list items](https://stackoverflow.com/questions/5080699/using-css-even-and-odd-pseudo-classes-with-list-items) – msanford Nov 14 '18 at 14:31

2 Answers2

8

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.

msanford
  • 11,803
  • 11
  • 66
  • 93
7

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.

xinthose
  • 3,213
  • 3
  • 40
  • 59
Wout
  • 94
  • 2