问题描述
在Ionic 5应用程序中,我必须通过离子滑块水平显示我的自定义组件,并在循环中垂直重复每个滑块。
接着输入代码。
<ng-container *ngFor="let item of mainList; let i = index;">
<ion-slides pager="true" loop="true" [options]="slideOpts" (ionSlideDidChange)="slideChanged(i)" #slides>
<ion-slide *ngFor="let id of item.subList; let j = index;">
<app-cust-comp [input]="j"></app-cust-comp>
</ion-slide>
</ion-slides>
</ng-container>
@ViewChild('slides') slides: IonSlides;
async slideChanged(i: number){
const activeSlideNumber = await this.slides.getActiveIndex();
console.log(i+' '+slideNumber);
}
我的目标是为每个索引获取正确的活动幻灯片编号。滑块工作正常,并且activeSlideNumber
的值每次仅对于第一个(索引0)滑块是正确的。对于除第一个滑块以外的所有滑块,activeSlideNumber
的值始终是第一个(索引0)滑块更改的最后一个值。因此,如果我将第一个(索引0)滑块滑动3次,而索引0的activeSlideNumber
为2,则所有其他滑块将始终为2。
解决方法
问题是视图中有ion-slider
的多个实例,但是ViewChild
仅用于获取滑块的一个实例。
您应该改用ViewChildren
:
@ViewChildren(IonSlides) slides: QueryList<IonSlides>;
请看看这个Stackblitz demo。
组件:
import { Component,QueryList,ViewChildren } from '@angular/core';
import { IonSlides } from '@ionic/angular';
@Component({
selector: 'app-home',templateUrl: 'home.page.html',styleUrls: ['home.page.scss']
})
export class HomePage {
@ViewChildren(IonSlides) slides: QueryList<IonSlides>; // <-- here!
// Some fake data...
public items = [
{
itemId: '1',subOptions: ['Option 1','Option 2','Option 3']
},{
itemId: '2',subOptions: ['Option 4','Option 5','Option 6']
},{
itemId: '3',subOptions: ['Option 7','Option 8','Option 9']
}
]
constructor() {}
public async slideChanged(i: number){
console.log(`Slider ${i} changed`);
// Iterate over the list of sliders to get all the selected indexes
this.slides.toArray().forEach(async (slider,index) => {
console.log(`Slider ${index} selected index: ${await slider.getActiveIndex()}`);
})
}
}
查看:
<ion-header>
<ion-toolbar>
<ion-title>
Home
</ion-title>
</ion-toolbar>
</ion-header>
<ion-content class="ion-padding">
<ng-container *ngFor="let item of items; let i = index">
<ion-slides pager="true" loop="true" (ionSlideDidChange)="slideChanged(i)">
<ion-slide *ngFor="let id of item.subOptions; let j = index;">
<p>(i: {{ i }} j: {{ j}}) {{ id }}</p>
</ion-slide>
</ion-slides>
</ng-container>
</ion-content>