【问题标题】:How to change the css class name dynamically in angular 2如何在角度2中动态更改css类名
【发布时间】:2017-01-23 06:11:12
【问题描述】:

我有两个CSS类名如下

.icon_heart{
     color: #bdbdbd;
}

.icon_heart_red{
    color:#a6b7d4;;
}

我的 HTML 有一个心形图标

<div class="icon_heart" *ngIf="showheartIcon">
    <ion-icon name="heart" (click)="setWishlistTrue(category.product_id);" class="heart"></ion-icon>
</div>
<div class="icon_heart_red" *ngIf="showheartIconRed">
    <ion-icon name="heart" (click)="setWishlistFalse(category.product_id);" class="heart"></ion-icon>
</div>

这里有两个 div 标签,心形图标最初是灰色,点击后我会将其更改为蓝色

这是我的 ts 文件代码:

  showheartIcon=true;
  showheartIconRed =false;

  setWishlistTrue(id){
    this.showheartIconRed = true;
    this.showheartIcon = false;
  }

  setWishlistFalse(id){
    this.showheartIconRed = false;
    this.showheartIcon = true;
  }

我有两个不同颜色的图标。

问题

是否可以更改图标的类别而不是两个心形图标?

我在 JavaScript 中看到我们可以更改它w3schools 将类应用于 div 标签的简单方法,但我是 TypeScript 的新手。如何更改班级?

【问题讨论】:

    标签: html css angular ionic2


    【解决方案1】:
    <div 
        [class.icon_heart]="!showheartIconRead"
        [class.icon_heart_red]="showheartIconRead">
    

    <div [ngClass]="showheartIconRead ? 'icon_heart_red' : 'icon_heart'">
    

    【讨论】:

    • 但是,如果您使用 ionic2 组件(如 ),这两个选项的工作方式不同 - [ngClass] 与 [class.xx] 的工作方式不同
    • 对不起-我再次检查-它们的工作方式相似(可能是其他问题的情况与我的情况不同)
    • 放置多个类:&lt;div [ngClass]="showheartIconRead ? 'icon_heart_red big' : 'icon_heart small'"&gt;
    • 使用 [ngClass]="..." 应该优先于 [class]="..."
    【解决方案2】:

    除了上面的答案。这也是可能的。

    <div class="{{showheartIconRead ? 'icon_heart_red' : 'icon_heart' }}">
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-22
      • 1970-01-01
      • 2018-02-16
      相关资源
      最近更新 更多