【问题标题】:Show different icon for first and different icon for remaining objects in html Angular8在 html Angular 8 中为第一个对象显示不同的图标,为剩余对象显示不同的图标
【发布时间】:2020-12-04 08:04:31
【问题描述】:

嗨,我有一个数组 = ideasArray 它共有 6 个对象。在 HTML 中,我想针对第一个对象的想法显示不同的图标,并为其余对象显示不同的图标。

<div class="container" *ngIf="let idea of ideasArray">
<ul class="data">
<li class="header"><i class="fas fa-medal"></i>Top Recommended Idea<li>
<li class="header"><i class="fas fa-thumbs-up"></i>Recommended Idea<li>
</ul>
</div>

我正在尝试为第一个对象显示不同的图标(TOP RECOMMENDED IDEA),其余的都将具有相同的图标(RECOMMENDED IDEA)。我该怎么做。从ideasArray 开始,第一个元素始终是最佳推荐创意,因此其标题应显示奖牌,其余部分应显示竖起大拇指。如何实现?

for (let j = 0; j < finalData.length; j++){
if(j<3){
this.firstThree.push(this.finalData[j]);
this.receivedData = this.firstThree;
} else if ((j >= 3) && (j <6)) {
this. nextThree.push(this.finalData[j]);
this.receivedData = this.nextThree;
}
}

【问题讨论】:

  • 您可以使用index 作为您的*ngFor(顺便说一下,不是*ngIf)。然后,如果 index=0 您将跳过分配图标。
  • 你能告诉我它如何适合这段代码吗?因为我不确定如何在
  • 标签中给出 index=0 以及为什么不使用 ngIf ?
  • 另外,如果 index=0 我不想跳过分配图标。我想分配一个不同的图标。
  • 你要对ul标签或li标签的哪一部分进行迭代?
  • 标签中我想检查它是否是第一个计划给奖牌其他人竖起大拇指
  • 标签: html arrays angular typescript angular8


    【解决方案1】:

    为此,最简单的方法是使用 use ngIf 结构指令。您可以像这样将它与数组的索引一起使用:-

    <div class="container" *ngFor="let idea of ideasArray; index as i">
    <ul class="data">
    <li *ngIf = "i == 0" class="header"><i class="fas fa-medal"></i>Top Recommended Idea<li>
    <li *ngIf = "i != 0" class="header"><i class="fas fa-thumbs-up"></i>Recommended Idea<li>
    </ul>
    </div>
    

    【讨论】:

      【解决方案2】:

      首先*ngIf是根据某些条件显示元素。您需要使用*ngFor 进行迭代或循环

      <div class="container" *ngFor="let idea of ideasArray; index as i">
         <ul class="data">
           <li *ngIf = "i == 0" class="header"><i class="fas fa-medal"></i>Top Recommended Idea<li>
          <li *ngIf = "i != 0" class="header"><i class="fas fa-thumbs-up"></i>Recommended Idea<li>
         </ul>
      </div>
      

      要了解更多关于如何使用structural directives,请参考Angular Structural Directive

      【讨论】:

      • 感谢您的回答。这几乎是正确的。只有一件事,我有一个轮播,所以 6 个对象显示在 2 页上。 3个。现在它将相同的样式应用于两个页面的第一个对象。我只想在第一页的第一个对象上获得最推荐的计划
      • 我正在通过更新代码来编写逻辑。你能告诉我如何避免这种情况吗?
      • 如果您正在处理两个不同的组件,那就是这样做的方法。
      猜你喜欢
      相关资源
      最近更新 更多
      热门标签