Search code examples
arraysangularionic-frameworkngforionic5

How to apply style to specific item in the array iterating using *ngFor when on click in Ionic using Angular


I'm trying to apply styling for a specific item in the iterable array when on click. The problem I'm facing is, it applies the style to the whole items in the array.

I want to apply the style dynamically only to that particular index when the button is clicked.

Below are excerpts from my code

HTML file

<ion-list>
  <ion-item-sliding *ngFor="let car of cars; let i=index;" #item>
    <ion-item [ngStyle]="car.sold || isSold ? {color: 'red'} : ''">
      <ion-label>{{car.name}}</ion-label>
    </ion-item>
    <ion-item-options icon-start>
      <button ion-button (click)="markAsSold(car, i, item)">
          Mark as Sold
        </button>
    </ion-item-options>
  </ion-item-sliding>
</ion-list> 

TS file

isSold = false; 

markAsSold(car, index, item){
  this.isSold = !car.sold;
  item.close();
}

I have created a working example using Stackblitz. Could anyone please help?


Solution

  • by attributing this.isSold and verifying car.sold || isSold it will return isSold wich is a global value to every item.

    You should verify the ngStyle without isSold, your sold logic should be attributed only for a specific item, if you change the flag: car.sold = !car.sold, and the ngStyle as car.sold ? {color: 'red'} : ''