问题
How do I add different classes for the inner elements in an ngFor loop in Angular 4? Say, I have a snippet:
<div *ngFor="let article of articles">
<div>
<h3>{{article.name}}</h3>
<p>{{article.body}}</p>
</div>
</div>
So I have 2 questions: how do I add different classes to the h3 elements in every generated article based on their order (first, second, third) and how do I add classes to the h3 elements based on odd-even order?
回答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?
来源:https://stackoverflow.com/questions/46590567/add-classes-within-ngfor-loop