如何在角度2中动态更改css类名

2022-01-13 00:00:00 html css angular ionic2

我有两个CSS类名如下

.icon_heart{颜色:#bdbdbd;}.icon_heart_red{颜色:#a6b7d4;;}

我的 HTML 有一个心形图标

<div class="icon_heart" *ngIf="showheartIcon">

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

这是我的 ts 文件代码:

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

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

问题

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

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

解决方案

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

I have two CSS class name as follows

.icon_heart{
     color: #bdbdbd;
}

.icon_heart_red{
    color:#a6b7d4;;
}

My HTML has a heart icon

<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>

Here I have two div tags, the heart icon is of gray color initially and on clicking that I will change it to blue color.

Here is my ts file code:

  showheartIcon=true;
  showheartIconRed =false;

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

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

I have two icons of different color.

Question

Instead of having two heart icons is it possible to change the class of the icon?

I have seen in JavaScript we can change it w3schools simple way to apply class to the div tag, but I am new to TypeScript. How can I change the class?

解决方案

<div 
    [class.icon_heart]="!showheartIconRead"
    [class.icon_heart_red]="showheartIconRead">

or

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

相关文章