简体   繁体   English

单击时如何仅更改离子列表中的一种离子项目颜色?

[英]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 .我有一个包含多个离子项目离子列表,我在 * 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).如您所见,我尝试在单击函数 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数组 -

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.在 onclick 函数中,发送已单击的数组的 id,并根据该 id 更改该对象的颜色。 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.取一个变量并检查*ngFor索引,如果项目被点击改变颜色。

.ts .ts

selectedItem: any;

.html .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.当 Item 被点击时更新你selectedItem变量并在你的ngStyle检查它以应用新的颜色。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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