Switch icon in ionic2 after click

夙愿已清 提交于 2020-01-17 03:05:10

问题


I have list of item, each of items has button with ion-icon

<ion-list>
        <ion-item *ngFor="let item of items">
          <ion-avatar item-left>
            <img src="{{item.logo}}" />
          </ion-avatar>

          <h2>{{item.name}}</h2>

            <button clear (click)="changeIcon(shop)" item-right>
                    <ion-icon name="ios-heart-outline" ></ion-icon>
            </button>
        </ion-item>
    </ion-list>

and I want to change this icon to ios-heart after click on button.


回答1:


Just like you can see in Ionic2 docs you can set the icon using a variable like this:

In your view:

<ion-icon [name]="myIcon"></ion-icon>

And then in your code:

export class MyFirstPage {
  // use the home icon
  myIcon: string = "home";
}

So in your case, I'd add the icon name to each element in the array

public items: [] = [
  {
    "logo" : "...",
    "name" : "...",
    "iconName" : "ios-heart-outline"
  },
  //...
];

Then in your view, I 'd change this part of the code:

<button clear (click)="changeIcon(item)" item-right>
  <ion-icon [name]="item.iconName" ></ion-icon>
</button>

Please notice that now in the changeIcon() method we receive the item so all we have to do is changing the name of the icon like this:

public changeIcon(theItem): void {
    theItem.iconName = "ios-heart";
} 


来源:https://stackoverflow.com/questions/38542395/switch-icon-in-ionic2-after-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!