'How to change the color of the font icons when we click on the particular icon in angular

In my angular application I have 10 icons and my requirement is to change the color from white to red when we click on the one icon among the 10 icons. And if we click on another icon it will turned to red ,and previous color changed icon(red) will be turned to white.

my code is

dashboard.component.html

<div class="container">
  <i class=" icon icon-smiley-face-1"></i>
 <i class=" icon icon-smiley-face-2"></i>
  <i class=" icon icon-smiley-face-3"></i>
  <i class=" icon  icon-smiley-face-4"></i>
<i class=" icon  icon-smiley-face-5"></i>
<i class=" icon  icon-smiley-face-6"></i>
</div>

Like the above I have 10 icons among the 10 icons if I click on one it will turned to red and at a time only one icon color has to change.

I know to change the one icon color but multiple icons I am unable to can anyone help me on this



Solution 1:[1]

I hope this helps. I have used event delegation here. For event delegation you can refer - https://www.youtube.com/watch?v=3KJI1WZGDrg&list=PLlasXeu85E9eLVlWFs-nz5PKXJU4f7Fks&index=8

or https://dmitripavlutin.com/javascript-event-delegation/

Let me know in case you need any explanation.

dashboard.component.html

<div class="container" (click)="onSelectIcon($event)">
    <i id="face-1" class="icon icon-smiley-face-1"></i>
    <i id="face-2" class="icon icon-smiley-face-2"></i>
    <i id="face-3" class="icon icon-smiley-face-3"></i>
    <i id="face-4" class="icon icon-smiley-face-4"></i>
    <i id="face-5" class="icon icon-smiley-face-5"></i>
    <i id="face-6" class="icon icon-smiley-face-6"></i>
</div>

dashboard.component.ts

prevSelectedIconId = ""
activeIconClass = "red" 

onSelectIcon(event) {

   const currSelectedIconId = event.target.id

   document.getElementById(currSelectedIconId).classList.add(activeIconClass)

   if (this.prevSelectedIconId && 
           this.prevSelectedIconId !== currSelectediconId)  {
     
      document.getElementById(this.prevSelectedIconId).classList.remove(activeIconClass)
   }

   this.prevSelectedIconId = event.target.id 
}

dashboard.component.scss

.red {     
   background-color : red;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1