最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

angular - Swiper Element (WebComponent) - how to use slideTo - Stack Overflow

programmeradmin4浏览0评论

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 badges
Add a comment  | 

1 Answer 1

Reset to default 1

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);
  }
}

发布评论

评论列表(0)

  1. 暂无评论