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 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.
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/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.
Share Improve this question edited yesterday MadMac asked yesterday MadMacMadMac 4,9258 gold badges44 silver badges82 bronze badges1 Answer
Reset to default 1You 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);
}
}