Search code examples
angulartypescriptonclickclickangular-directive

How to change the color of a icon among multiple icons one at a time using click event in angular


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 class="container">
<span class="icon-number"></span><i class="smiley  icon-face-1"></i>
        <span class="icon-number"></span><i class="smiley  icon-face-2"></i>
        <span class="icon-number"></span><i class="smiley  icon-face-3"></i>
        <span class="icon-number"></span><i class="smiley  icon-4"></i>
        <span class="icon-number"></span><i class="smiley icon-face-5"></i>
        <span class="icon-number"></span><i class="smiley icon-face-6"></i>
</div>

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


Solution

  • <div class="container">
        <button *ngFor="let btn of btnArr" type="button" class="buttonstyle"
            [style.background-color]="selectedButton === btn ? '#FF0000' : 'grey'" (click)="selectedButton = btn">
            {{btn}}
        </button>
    </div>
    
    <div class="container">
        <i (click)="selectedIcon = icon.id" class="smiley" [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;