在ngFor循环中添加类 [英] Add classes within ngFor loop

查看:69
本文介绍了在ngFor循环中添加类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Angular 4的ngFor循环中为内部元素添加不同的类?说,我有一个摘要:

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>

所以我有2个问题:如何根据每个生成的文章的顺序(第一,第二,第三)向h3元素添加不同的类,以及如何基于奇偶顺序向h3元素添加类?

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?

推荐答案

您可以在 ngClass 结合起来,您可以设置课程.

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.

正如@ Paco0所指出的那样,也许您是说id="article"id="{{article.id}}"还是类似的意思?

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

这篇关于在ngFor循环中添加类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆