Add classes within ngFor loop

試著忘記壹切 提交于 2020-01-15 08:56:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!