15

I have two CSS class names as follows.

.icon_heart{
     color: #bdbdbd;
}

.icon_heart_red{
    color: #a6b7d4;;
}

My HTML contains 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>

There are two div elements. The heart icon has a grey colour until the user clicks it, then it should change to blue.

The following block of code is from my TypeScript file; two icons with different colours.

  showheartIcon = true;
  showheartIconRed = false;

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

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

Is it possible to replace the class of the icon, instead of having two of them?

I have seen in JavaScript that I can add a class to any HTML element.

How can I achieve that in Angular?

2 Answers 2

23

You can change CSS class names using the following options.

Option 1

<div 
    [class.icon_heart]="!showheartIconRed"
    [class.icon_heart_red]="showheartIconRed">This is an example.</div>

Option 2

<div [ngClass]="showheartIconRed ? 'icon_heart_red' : 'icon_heart'">This is another example.</div>
Sign up to request clarification or add additional context in comments.

4 Comments

However if you use ionic2 components (like <ion-textarea>) this two options not work similar - [ngClass] will work differently than [class.xx]
sorry - i check this again - and they work similar (probably the other problem case different behaviour in my case)
To place multiple classes: <div [ngClass]="showheartIconRead ? 'icon_heart_red big' : 'icon_heart small'">
Using [ngClass]="..." should be pregerred onver [class]="..."
8

You can use the following method in addition to the answer above.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.