【问题标题】:Angular ngFor with ngClassAngular ngFor 和 ngClass
【发布时间】:2019-02-23 19:10:07
【问题描述】:

我有一个包含天气条件的数组和一个包含与天气条件相同大小的图标类名称的数组。我想用 iconNames[i] 的类名显示“i”标签。我该怎么做?

<li *ngFor="let item of weather; let i = index">
  <h1>{{ item.valid_date }}</h1>
  <h2>{{ item.temp }}</h2>
  <i [ngClass]="{iconNames[i]}"></i>
</li>

【问题讨论】:

  • 你试过这个,没有{{}}

标签: angular ngfor ng-class


【解决方案1】:

您可以为此使用class binding

<li *ngFor="let item of weather; let i = index">
  <h1>{{ item.valid_date }}</h1>
  <h2>{{ item.temp }}</h2>
  <i [class]="iconNames[i]"></i>
</li>

【讨论】:

    【解决方案2】:

    要使用ngClass,您可以在组件中创建函数并在*ngFor 中调用它以获取动态值

    getClassName(i) {
        return iconNames[i];
    }
    

    在html中调用

    <li *ngFor="let item of weather; let i = index">
      <h1>{{ item.valid_date }}</h1>
      <h2>{{ item.temp }}</h2>
      <i [ngClass]="getClasses(i)"></i>
    </li>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-01-27
      • 1970-01-01
      • 2016-07-22
      • 2020-10-23
      • 2018-08-01
      • 2016-07-14
      • 2018-01-29
      • 1970-01-01
      相关资源
      最近更新 更多