单击离子更改图像?
Ionic change image on click?
我想在单击按钮时更改图像。
我做了这个:
home.html
<div class="card">
<img [src]="cards.img" />
</div>
<ion-button (click)="logEvent($event)">
<ion-icon slot="icon-only" name="checkmark-outline"></ion-icon>
</ion-button>
</ion-content>
和我的home.ts
export class HomePage implements OnInit {
cards;
constructor() {
this.cards = [];
}
ngOnInit() {}
logEvent(event) {
console.log("click");
this.cards = [
{
img: "https://placeimg.com/300/300/people",
},
{
img: "https://placeimg.com/300/300/animals",
},
];
}
}
不过我也只能到此为止了。
问题就在这里<img [src]="cards.img" />
。您正在尝试读取数组的 .img
,而不是单个卡片。
在您的 class 上有一个 selectedCardIndex
变量,在单击按钮时,您需要设置 selectedCardIndex 值。
您可以将代码更改为以下以使其工作:
<div class="card">
<img [src]="cards[selectedCardIndex].img" />
</div>
<ion-button (click)="logEvent($event)">
<ion-icon slot="icon-only" name="checkmark-outline"></ion-icon>
</ion-button>
export class HomePage implements OnInit {
cards;
selectedCardIndex = 0;
constructor() {
this.cards = [
{
img: "https://placeimg.com/300/300/people",
},
{
img: "https://placeimg.com/300/300/animals",
},
];
}
ngOnInit() {}
logEvent(event) {
const newIndex = this.selectedCardIndex + 1;
if (newIndex === this.cards.length) {
this.selectedCardIndex = 0;
} else {
this.selectedCardIndex = newIndex;
}
}
}
我想在单击按钮时更改图像。
我做了这个:
home.html
<div class="card"> <img [src]="cards.img" /> </div> <ion-button (click)="logEvent($event)"> <ion-icon slot="icon-only" name="checkmark-outline"></ion-icon> </ion-button> </ion-content>
和我的home.ts
export class HomePage implements OnInit {
cards;
constructor() {
this.cards = [];
}
ngOnInit() {}
logEvent(event) {
console.log("click");
this.cards = [
{
img: "https://placeimg.com/300/300/people",
},
{
img: "https://placeimg.com/300/300/animals",
},
];
}
}
不过我也只能到此为止了。
问题就在这里<img [src]="cards.img" />
。您正在尝试读取数组的 .img
,而不是单个卡片。
在您的 class 上有一个 selectedCardIndex
变量,在单击按钮时,您需要设置 selectedCardIndex 值。
您可以将代码更改为以下以使其工作:
<div class="card">
<img [src]="cards[selectedCardIndex].img" />
</div>
<ion-button (click)="logEvent($event)">
<ion-icon slot="icon-only" name="checkmark-outline"></ion-icon>
</ion-button>
export class HomePage implements OnInit {
cards;
selectedCardIndex = 0;
constructor() {
this.cards = [
{
img: "https://placeimg.com/300/300/people",
},
{
img: "https://placeimg.com/300/300/animals",
},
];
}
ngOnInit() {}
logEvent(event) {
const newIndex = this.selectedCardIndex + 1;
if (newIndex === this.cards.length) {
this.selectedCardIndex = 0;
} else {
this.selectedCardIndex = newIndex;
}
}
}