简体   繁体   中英

How to change only one ion-item color in ion-list when clicked?

I have tried multiple things but I can't seem to figure this one out. I have an ion-list with multiple ion-items that I get from an array with the help of * ngFor . When I click on one item, I only want its' color to be changed. I've managed to be able to change all the ion-item colors when I click one of them but that's not what I want.

This is a code snippet:

      <ion-col>
         <ion-item *ngFor="let exercise of exercisesArray" (click)="onClick(exercise)"  [ngStyle]="{color: color}"> 
          {{exercise.title}}
        </ion-item>
      </ion-col>
    </ion-list>

As you can see, I tried changing the color variable when clicking in the function onClick(exercise). I need the exercise as a parameter for other purposes. Anyways, that works but all the items in the exerciseArray get that color. But as I said, I would like to only change the color of the item that has been clicked.

Thank you in advance for your help!

In order to do that, create the exercisesArray like this for example -

exercisesArray = [
    {
      title: "A",
      color: "green"
    },
    {
      title: "B",
      color: "green"
    },
    {
      title: "C",
      color: "green"
    }
  ];

and in onclick function, send the id of the array that has been clicked and based on that id, change the color of that object. for example,

this.exercisesArray[index].color = 'red';

For further reference, take a look at this

Take a Variable and check index of your *ngFor if item gets clicked change color.

.ts

selectedItem: any;

.html

<ion-item *ngFor="let exercise of exercisesArray; let i = index" (click)="onClick(exercise); selectedItem = i"  [ngStyle]="{color: selectedItem == i ? YourNewColor : null}">
{{exercise.title}}
</ion-item>

update you selectedItem variable when Item gets clicked and check it in your ngStyle to apply new Color.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM