How to change the color of only one button?

I have a problem. I made a button loop in HTML. So now I want them to change color when I press the button. But I have a problem that they all change color. But I want to change the color of the pressed button.

HTML

 <ion-item *ngFor="let friend of friendsList">
      <ion-avatar item-start>
        <img src={{friend.img}}>
      </ion-avatar>
      <button ion-button color="rank" class="avat"> </button>
      <h2>{{friend.name}}</h2>
      <p>{{friend.status}}</p>
      <button (click)="toggleNamedColor()" ion-button round color="rank" [color]="ionicNamedColor" item-end>+Add</button>

    </ion-item>

  </ion-list> 

TS

public ionicNamedColor: string = 'rank';

public toggleNamedColor(): void {
      if(this.ionicNamedColor === 'rank') { 
        this.ionicNamedColor = 'primary'
      } else {
        this.ionicNamedColor = 'rank'
      }
    }
+4
source share
2 answers

You can try this, like this example, by adding a color property to the object and changing the color property of this object when you click

 <ion-list> 
    <ion-item *ngFor="let friend of friendsList">
          <ion-avatar item-start>
            <img src={{friend.img}}>
          </ion-avatar>
          <button ion-button color="rank" class="avat"> </button>
          <h2>{{friend.name}}</h2>
          <p>{{friend.status}}</p>
          <button (click)="toggleNamedColor(friend)" ion-button round color="rank" [color]="friend.ionicNamedColor" item-end>+Add</button>

        </ion-item>

      </ion-list>

And in ts

public toggleNamedColor(friend): void {
      if(friend.ionicNamedColor === 'rank') { 
        friend.ionicNamedColor = 'primary'
      } else {
        friend.ionicNamedColor = 'rank'
      }
  }
0
source

Try with an index in ngFor

Html

<ion-item *ngFor="let friend of friendsList;let i = index">
      <ion-avatar item-start>
        <img src={{friend.img}}>
      </ion-avatar>
      <button ion-button color="rank" class="avat"> </button>
      <h2>{{friend.name}}</h2>
      <p>{{friend.status}}</p>
      <button (click)="curIndex = i" ion-button round [color]="curIndex == i ? 'rank' : 'primary'" item-end>+Add</button>

    </ion-item>

declare this variable in a .ts file

curIndex:number = null;

Refer to the stackblitz demo

0
source

Source: https://habr.com/ru/post/1695804/