Swiper - Ionic -Angular:从最后一张幻灯片滚动到第一张幻灯片时索引不会重置

问题描述 投票:0回答:1

当用户可以滚动选择他的体重时,我使用滑动器创建一个滑动数字数组。 Swiper 有

[loop]="true"
我的问题是,一旦用户达到我的情况滑块 7 的限制并移动到滑块 1,索引也不会重新启动到索引 0,而且如果我从幻灯片 1 向后滚动到 7,我也没有更新索引在我的例子中等于 6。拥有正确的索引非常重要,因为基于它我更新了所选值。

我怎样才能实现以下目标/意图?

这是我的实际代码:

这是我的

component.html

<ion-row>
    <ion-col size="10">
      <swiper-container
        #slides
        [options]="sliderOptionsOpts"
        [modules]="swiperModules"
        (swiperslidechange)="checkRangeSlide($event)"
        [loop]="true"
        style="height: 200px"
      >
        <swiper-slide *ngFor="let option of sliderOptions">
          <span
            [ngClass]="option === sliderSelected ? 'fw-bold' : 'text-muted'"
            class="fs-1"
            >{{ option }}</span
          >
        </swiper-slide>
      </swiper-container>
    </ion-col>

这是我的

component.ts

sliderOptions: number[] = [];
  sliderOptionsOpts: any;
  sliderSelected: number = 1;

  checkMinMaxRange(max: number, min: number) {
    console.log("max min", max, min);
    const dataArray = this.createArrayFromRange(1, 7);
    this.sliderOptions = dataArray;
    this.sliderOptionsOpts = {
      slidesPerView: 1,
      centeredSlides: true,
      reverseDirection: true,
      initialSlide: this.sliderOptions.indexOf(this.sliderSelected),
      loop: true,
    };
  }

  createArrayFromRange(min: number, max: number): number[] {
    const length = max - min + 1;
    return Array.from({ length }, (_, index) => index + min);
  }

  checkRangeSlide(event: any) {
    let activeIndex = event.detail[0].realIndex;
    const selectedValue = this.sliderOptions[activeIndex];
    const answerObject = {
      selectedValue: selectedValue + 1,
      activeIndex: activeIndex,
      object: event.detail[0],
    };
    console.log("ANSWER:", answerObject);
  }
javascript angular typescript ionic-framework swiper.js
1个回答
0
投票

要获得正确的索引,您可以执行此实现:

import { Component, OnInit, CUSTOM_ELEMENTS_SCHEMA, ViewChild, ElementRef, NgZone } from '@angular/core';

export class YourComponent implements OnInit {

@ViewChild('slides') slidesRef!: ElementRef<any>;
activeIndex: number = 0;


swiperSlideChanged(e: any) {
    this.zone.run(() => {
      this.activeIndex = this.slidesRef.nativeElement.swiper.activeIndex;
       // your other logic
    })
  }

}


© www.soinside.com 2019 - 2024. All rights reserved.