循环中的多个离子载玻片无法在载玻片上提供正确的索引

问题描述

在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

Demo gif

组件:

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>

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...