Akram Magdy
Akram Magdy

Reputation: 1

How to change icon color when i clicked on button?

How do I change the color of icon on click?

Is using the ngClass is the best option?

What I have done so far is assign a class to my icon.

<ion-card>
    <ion-row>
        <ion-col>
            <button ion-button icon-left clear small>
                <ion-icon name="eye" #name [ngClass]="{
                'isActive' : isActive}" (click)="activeCheck(name)">
                </ion-icon>
            </button>
        </ion-col>
    </ion-row>
</ion-card>

.ts file

export class NewsPage implements OnInit {
    isActive: boolean = false;

    activeCheck(name) {
        console.log(name);
        this.isActive = !this.isActive;
    }
}

Upvotes: 0

Views: 1675

Answers (2)

SiddAjmera
SiddAjmera

Reputation: 39482

You don't really need a function for this. You can simply toggle the value of isActive property in the template.

Also, make the (click) event handler on the button instead of the ion-icon.

And, use [class.isActive]="isActive" for a shorter syntax.

Here's the code:

<ion-row>
  <ion-col>
    <button 
      ion-button 
      icon-left 
      clear 
      small 
      (click)="isActive = !isActive">
      <ion-icon 
        name="eye" 
        #name 
        [class.isActive]="isActive">
      </ion-icon>
    </button>
  </ion-col>
</ion-row>

Here's a Working Sample StackBlitz for your ref.

Upvotes: 0

Harshana
Harshana

Reputation: 534

Add some styles for activated class and following does the job. ngClass adding the class dynamically based on value of isActive variable. You can use isActive value change for (click) instead of using a function call.

<ion-icon name="eye" #name [ngClass]="isActive ? 'activated' : ''" (click)="isActive = !isActive">
</ion-icon>

Upvotes: 1

Related Questions