【问题标题】:Add classes within ngFor loop在 ngFor 循环中添加类
【发布时间】:2017-10-05 16:28:16
【问题描述】:

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

<div *ngFor="let article of articles">
  <div>
    <h3>{{article.name}}</h3>
    <p>{{article.body}}</p>
  </div>
</div>

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

【问题讨论】:

  • 只是附带说明:您正在为所有循环 div 设置相同的 id,即字符串 "article",这可能会让您陷入其他错误。
  • 谢谢,实际上不应该存在

标签: javascript angular frontend


【解决方案1】:

您可以在ngForOf 中获取当前迭代的索引、奇数和偶数,将其与ngClass 结合,您可以设置类。

<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}}" 或类似的东西?

【讨论】:

  • isEven 是默认功能吗?
  • 只要 id 只是一个 html 属性,“article.id”将是字符串 "article.id",而不是实际的文章 id。需要像 id="{{article.id}}" 这样的东西来进行评估。
  • @artgb - 不,evenisEveneven 的别名。
  • 谢谢,有道理
猜你喜欢
  • 2018-11-05
  • 2017-03-30
  • 2017-07-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-10
  • 1970-01-01
  • 2021-06-11
相关资源
最近更新 更多