Skip to content Skip to sidebar Skip to footer

Add Classes Within NgFor Loop

How do I add different classes for the inner elements in an ngFor loop in Angular 4? Say, I have a snippet:

Solution 1:

You can get the index, odd, and even of the current iteration in the ngForOf, combine that with ngClass and you can set the class.

<div *ngFor="let article of articles; index as i; even as isEven; odd as isOdd">
  <div id="article">
    <h3 [ngClass]="{'odd': isOdd, 'even': isEven}">{{article.name}}</h3>
    <p>{{article.body}}</p>
  </div>
</div>

You do not mention how you want to use the index/position so there is no code for that. I am sure you can figure that part out though based on the sample code above and documentation.


As @Paco0 also pointed out maybe you meant id="article" to be id="{{article.id}}" or something similar?


Post a Comment for "Add Classes Within NgFor Loop"