Home > Software design >  How to change the color of the font icons when we click on the particular icon in angular
How to change the color of the font icons when we click on the particular icon in angular

Time:02-04

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 >
  <i ></i>
 <i ></i>
  <i ></i>
  <i ></i>
<i ></i>
<i ></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

CodePudding user response:

I hope this will help- You should use the following syntax:

<div (click)="onClick()">
   <i  [ngClass]="{'active': isActive}"></i>
</div>

CodePudding user response:

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  (click)="onSelectIcon($event)">
    <i id="face-1" ></i>
    <i id="face-2" ></i>
    <i id="face-3" ></i>
    <i id="face-4" ></i>
    <i id="face-5" ></i>
    <i id="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;
}
  •  Tags:  
  • Related