-1

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

user93
  • 39
  • 1
  • 4

1 Answers1

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;
}
  • Thanks@Sapna Kumari ,How I can add the preSelectedIconId and activeIconClass = "red" in scss .And It would be helpful for me if you write the above using ngClass for toggle in angular.Can you help me on this – user93 Feb 03 '22 at 09:44
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Feb 03 '22 at 10:21
  • @user93 You just need to add class 'red' in .scss file. preSelectedIconId and activeIconClass are variables declared in .ts file. I will add .scss file code for better clarity. – Sapna Kumari Feb 03 '22 at 11:25