我想创建一个单击以显示下一个图片库以显示下一张图片,感觉就像一个画廊。我正在尝试将“绑定数据”绑定到子级方法。但是当我单击其中一张图像时,每张图像都绑定到数据,并显示相同的图片。我正在尝试更改一张图片。
这是html的样子。我使用ngFor.
<ion-slide *ngFor='let voucher of vouchers; let i=index'>
<ion-card class='slide-card'>
<ion-row class='image-box-row' align-items-end>
<ion-col no-padding>
<span class='image-box'>
<img id='switchableImage' [src]='imageUrl' (click)='switchImage(i)'>
</span>
</ion-col>
</ion-row>
<ion-row class='bottom-content-row'>
<ion-col class='bottom-content' text-left>
<span id='voucherName'>{{voucher.voucherName}}</span>
<span id='quantitySold'>{{voucher.quantitySold}} Sold</span>
</ion-col>
</ion-row>
</ion-card>
</ion-slide>
这是ts文件,为“ imageUrl”分配了对象数组中的值。
switchImage(i) {
console.log('slides ' + i + ' is tapped');
this.counter += 1;
console.log('counter is ' + this.counter);
if (this.counter > this.vouchers[i].voucherImages.length -1) {
this.counter = 0;
}
console.log(this.vouchers[i].voucherImages[this.counter]);
this.imageUrl = this.vouchers[i].voucherImages[this.counter];
}
我的对象数组看起来像这样
public vouchers: any = [
{
voucherId: 1,
restaurantId: 1,
voucherImages: [
'../../assets/imgs/set1.jpg',
'../../assets/imgs/set1_2.jpg'
],
voucherName: 'Valuable One Person Set Meal',
suitablePax: 1,
quantitySold: 119,
newPrice: 20,
basePrice: 25,
currency: 'RM'
},
{
voucherId: 2,
restaurantId: 1,
voucherImages: [
'../../assets/imgs/set2.jpeg',
'../../assets/imgs/set2_2.jpg',
'../../assets/imgs/set2_3.jpg'
],
voucherName: 'Romantic Two Person Steak Meal',
suitablePax: 2,
quantitySold: 119,
newPrice: 89.9,
basePrice: 120,
currency: 'RM'
}
]
还是你们有更好的方法来单击切换图像库?我没有留下太多的脑汁。
答案 0 :(得分:1)
首先,向每个凭证对象添加一个新属性,它将成为每个凭证库的索引:
{
voucherId: 1,
restaurantId: 1,
voucherImages: [
'../../assets/imgs/set1.jpg',
'../../assets/imgs/set1_2.jpg'
],
voucherName: 'Valuable One Person Set Meal',
suitablePax: 1,
quantitySold: 119,
newPrice: 20,
basePrice: 25,
currency: 'RM'
index: 0
}
然后,在HTML的图片来源上,设置voucherImages和选定的索引。
<img id='switchableImage' [src]='voucher.voucherImages[voucher.index]' (click)='switchImage(i)'>
只需在每次点击时增加凭证索引:
switchImage(i) {
console.log('slides ' + i + ' is tapped');
this.vouchers[i].index += 1;
console.log('counter is ' + this.vouchers[i].index);
if (this.vouchers[i].index > this.vouchers[i].voucherImages.length -1) {
this.vouchers[i].index = 0;
}
console.log(this.vouchers[i].voucherImages[this.vouchers[i].index]);
}
index属性取代了您的计数器