MadMac
MadMac

Reputation: 4993

Swiper Element (WebComponent) - how to use slideTo

I have updated my angular version from 12 to 16 for my Ionic project and have had to update the slider component.

I am using the Swiper Element (WebComponent) v11.2.4 https://swiperjs.com/element and I need to programmatically move to a slide the same way I was with the older swiper. Previously I was using

this.swiper.setIndex(arrayIndex)

I have tried the below but it does not work. Any suggestions?

@ViewChild('swiperContainer', { static: false }) swiperContainer: ElementRef;

this.swiperContainer.nativeElement.slideTo(arrayIndex, 0, false);

Update

I got it working using:

this.swiperContainer.nativeElement.swiper.slideTo(arrayIndex, 0, false);

But curious if there is a better way.

Upvotes: 0

Views: 31

Answers (1)

Shailesh
Shailesh

Reputation: 196

You can try this way:

  • Avoids nativeElement Access → Directly working with the SwiperContainer type ensures type safety.
  • More Maintainable → TypeScript will provide better autocomplete and error-checking.
  • Future-Proofing → Reduces reliance on ElementRef, making it more compatible with Angular best practices.

import { Component, ViewChild, AfterViewInit } from '@angular/core';
import { SwiperContainer } from 'swiper/element';

@Component({
  selector: 'app-example',
  template: `<swiper-container #swiperContainer></swiper-container>`,
})
export class ExampleComponent implements AfterViewInit {
  @ViewChild('swiperContainer', { static: false }) swiperContainer!: SwiperContainer;

  ngAfterViewInit() {
    this.swiperContainer.swiper.slideTo(2, 0, false);
  }

  goToSlide(index: number) {
    this.swiperContainer.swiper.slideTo(index, 0, false);
  }
}

Upvotes: 1

Related Questions