How to change the css class name dynamically in angular 2
29,886
Solution 1
<div
[class.icon_heart]="!showheartIconRead"
[class.icon_heart_red]="showheartIconRead">
or
<div [ngClass]="showheartIconRead ? 'icon_heart_red' : 'icon_heart'">
Solution 2
In addition to the above answer. this is also possible.
<div class="{{showheartIconRead ? 'icon_heart_red' : 'icon_heart' }}">
Author by
Mohan Gopi
Each and every end of the day thinking what i have learned today. And Improving my self daily as developer.
Updated on March 16, 2020Comments
-
Mohan Gopi about 4 years
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?
-
Kamil Kiełczewski almost 7 yearsHowever if you use ionic2 components (like <ion-textarea>) this two options not work similar - [ngClass] will work differently than [class.xx]
-
Kamil Kiełczewski almost 7 yearssorry - i check this again - and they work similar (probably the other problem case different behaviour in my case)
-
Tadija Bagarić over 6 yearsTo place multiple classes:
<div [ngClass]="showheartIconRead ? 'icon_heart_red big' : 'icon_heart small'">
-
Günter Zöchbauer about 6 yearsUsing
[ngClass]="..."
should be pregerred onver[class]="..."