Home > Back-end >  How to change the color of a icon among multiple icons one at a time using click event in angular
How to change the color of a icon among multiple icons one at a time using click event in angular

Time:02-07

I have an angular application In that I have added 6 icons .My requirement is when I click on any button the particular icon color should changed from gray red color, and when I click on other icon the other icon changed to red color and previous color changed button should changed to gray color.

and my angular code is:

.component.html

<div >
<span ></span><i ></i>
        <span ></span><i ></i>
        <span ></span><i ></i>
        <span ></span><i ></i>
        <span ></span><i ></i>
        <span ></span><i ></i>
</div>

So Can any one help me how to change the color of particular icon using click event in angular.

CodePudding user response:

<div >
    <button *ngFor="let btn of btnArr" type="button" 
        [style.background-color]="selectedButton === btn ? '#FF0000' : 'grey'" (click)="selectedButton = btn">
        {{btn}}
    </button>
</div>

<div >
    <i (click)="selectedIcon = icon.id"  [ngClass]="icon.class"
        [style.color]="selectedIcon === icon.id ? '#FF0000' : '#000000'" *ngFor="let icon of iconsArr"></i>
</div>

In component ts file

btnArr = ["BUTTON-1", "BUTTON-2", "BUTTON-3", "BUTTON-4", "BUTTON-5", "BUTTON-6"];
selectedButton = "";

iconsArr = [
        { id: 1, class: "icon-face-1" },
        { id: 2, class: "icon-face-2" },
        { id: 3, class: "icon-face-3" },
        { id: 4, class: "icon-face-4" },
        { id: 5, class: "icon-face-5" },
        { id: 6, class: "icon-face-6" }
    ];
    selectedIcon = 0;

CodePudding user response:

In Component.ts File Take on a variable and name it as currentButton=''

Also, make on function on .ts side will set the current button

SetCurrentButton(buttonValue:string){
this.currentButton=buttonValue;
}

Now From Html In Your Button Code do Below Change

<div >

 <button type="button"  (click)="SetCurrentButton(btn1)" [ngStyle]="{'color':currentButton === 'btn1' ? 'red' : '' }">
          BUTTON-1
        </button>
        <button type="button"  (click)="SetCurrentButton(btn2)" [ngStyle]="{'color':currentButton === 'btn2' ? 'red' : '' }">
          BUTTON-2
        </button>
        <button type="button"  (click)="SetCurrentButton(btn3)" [ngStyle]="{'color':currentButton === 'btn3' ? 'red' : '' }">
          BUTTON-3
        </button>
 <button type="button"  (click)="SetCurrentButton(btn4)" [ngStyle]="{'color':currentButton === 'btn4' ? 'red' : '' }">
          BUTTON-4
        </button>
 <button type="button"  (click)="SetCurrentButton(btn5)" [ngStyle]="{'color':currentButton === 'btn5' ? 'red' : '' }">
          BUTTON-5
        </button>
<button type="button"  (click)="SetCurrentButton(btn6)" [ngStyle]="{'color':currentButton === 'btn6' ? 'red' : '' }">
          BUTTON-6
        </button>
</div>
  •  Tags:  
  • Related