如何在 Angular 4 的 ngFor 循环中为内部元素添加不同的类?说,我有一个片段:
<div *ngFor="let article of articles">
<div>
<h3>{{article.name}}</h3>
<p>{{article.body}}</p>
</div>
</div>
所以我有两个问题:如何根据顺序(第一、第二、第三)向每篇生成的文章中的 h3 元素添加不同的类,以及如何根据奇偶顺序向 h3 元素添加类?
最佳答案
您可以在ngForOf 中获取当前迭代的索引、奇数和偶数。 , 将其与 ngClass 相结合你可以设置类(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>
你没有提到你想如何使用索引/位置,所以没有代码。我相信您可以根据上面的示例代码和文档弄清楚这部分内容。
正如@Paco0 也指出的,也许您的意思是 id="article"
是 id="{{article.id}}"
或类似的东西?
关于javascript - 在 ngFor 循环中添加类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46590567/