How to change color of only single element in Angular

Viewed 288

I have rendered buttons inside a list. I would like to change their color when i click on them. But when I click it changes the color for all the buttons in that list. But I only want to change the single button icon.

This my html

<li *ngFor="let datum of filteredData; let i = index">
        <button mat-mini-fab (click)="onLike(datum);onToggle()" [style.background-color]="toggle ? 'green' : 'red'">
            <mat-icon svgIcon="check" aria-hidden="false" aria-label="Example thumbs up SVG icon"></mat-icon>
        </button>
</li>

And here is my ts logic

toggle=true;
onToggle() {
    this.toggle = !this.toggle;
  }

Any help would be appreciated!

1 Answers

So, you obviously need to keep a track of buttons clicked. and change the color based on state of tracker. This can easily be done as,

Step 1: Introduce a tracking variable

public clicked: {[key: number]: boolean} = {};

Step 2: Change onToggle function to

public onToggle(i): void {
   // Switch between red and green.
   this.clicked[i] = !this.clicked[i];
}

or

public onToggle(i): void {
   // always green
   this.clicked[i] = true;
}

Step 3: Change function call to pass a unique ID pre click:

<li *ngFor="let datum of [1,2,3]; let i = index">
    <button (click)="onToggle(i)" 
            [style.background-color]="clicked[i] ? 'green' : 'red'">
            {{ i }}
     </button>
</li>

This code is now ready to rock!!!

Related