Raphaël Balet
Raphaël Balet

Reputation: 8553

How to get swiper autoplayTimeLeft in Angular

I'd like to create my own pagination, with a bar filling himself while the autoplay is playing

enter image description here

I see that swiper do have an autoplayTimeLeft method, but I cannot figure out how to use it.

This is what I've tried so fare, but the method wont trigger anything.

<swiper-container #swiperRef init="false" (autoplayTimeLeft)="setTimeLeft($event)">
</swiper-container>

I'm instantiating the swiper as follow

Upvotes: 1

Views: 999

Answers (2)

Rapha&#235;l Balet
Rapha&#235;l Balet

Reputation: 8553

As I show in the image in my question, I've needed to know the active index for me to be able to show the white line with css.

The autoplay feature have sadly a little bug and it is impossible to get the correct swiper.activeIndex since it does never reset to 0.

I had to implement a custom feature and wished to share it with you.

percentage:number = 0
activeIndex = 0
defaultDelay = 500
slides = ['1', '2', '3']

private _initSwiper() {
  const options: SwiperOptions = {...}

  const swiperEl = this._swiperRef.nativeElement
  Object.assign(swiperEl, options)

  swiperEl.initialize()

  if (this.swiper) this.swiper.currentBreakpoint = false // Breakpoint fixes
  this.swiper = this._swiperRef.nativeElement.swiper
  
  // Custom Autoplay Time
  this.doAutoplay(this.defaultDelay, this.activeIndex)

  // If the user manually change the slide
  this.swiper.on('slideChange', (swiper: Swiper) => {
    this.activeIndex = swiper.activeIndex
    this.doAutoplay(this.defaultDelay, this.activeIndex)
  })
}


doAutoplay(delay: number, index: number) {
  if (this.activeIndex !== index) return

  this.percentage = 100 - (delay / this.defaultDelay) * 100 + '%'

  if (delay <= 0) {
    setTimeout(() => {
      if (this.activeIndex + 1 === this.slides.length) this.swiper.slideTo(0)
      else this.swiper.slideTo(this.activeIndex + 1)
    }, 300)
    return
  }

  setTimeout(() => {
    this.doAutoplay(delay - 10, index)
  }, 10)
}

Upvotes: 0

Adora Gonz&#225;lez
Adora Gonz&#225;lez

Reputation: 139

You should use it as an event. Then, in the _initSwiper() method, you can do the following:

percentage:number=0;
private _initSwiper() {
  const options: SwiperOptions = {...}

  const swiperEl = this._swiperRef.nativeElement
  Object.assign(swiperEl, options)

  swiperEl.initialize()

  if (this.swiper) this.swiper.currentBreakpoint = false // Breakpoint fixes
  this.swiper = this._swiperRef.nativeElement.swiper
  
  // Autoplay Time Left Event
  this.swiper.on('autoplayTimeLeft',(swiper:Swiper, timeLeft:number, percentage:number)=>{
    // Here write the code you need
    console.log(swiper, timeLeft, percentage);
    this.percentage=percentage;
  });
}

Here's an example similar to what you want to achieve.

Upvotes: 2

Related Questions