0

在我的 Ionic 5 应用程序中,我必须通过 ion-slides 水平显示我的自定义组件,并在循环中垂直重复每个滑块。

在代码中。

<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 次,activeSlideNumber索引 0 的值为 2。对于所有其他滑块,它将始终为 2。

4

1 回答 1

2

问题是ion-slider您的视图中有多个实例,但ViewChild仅用于获取滑块的一个实例。

您应该ViewChildren改用:

@ViewChildren(IonSlides) slides: QueryList<IonSlides>;

请看一下这个Stackblitz 演示

演示 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>

于 2020-10-12T07:21:06.347 回答