Reputation: 1062
I have a problem. I made a loop with buttons in HTML. So now I want them to change the color when I press the button. But I have the problem that they all change the color. But I only want to change the color of the button that was pressed.
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'
}
}
Upvotes: 5
Views: 445
Reputation: 4480
You could try it like this example by adding color property to the object and change color property of that object on 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'
}
}
Upvotes: 1
Reputation: 2093
Please try with 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 .ts file
curIndex:number = null;
Refer stackblitz demo
Upvotes: 0