angularionic-frameworkswiper.jsionic6

(Ionic / Angular) Swiper.js Autoplay is not running


ā€”ā€” Issue ā€”ā€”

Hello, I dont understand why swiper is not starting like autoplay must be.

When I look into the swiper instance from (swiper) event, I got this results :

  1. swiper.params.autoplay: {delay: 1000, enabled: true}
  2. swiper.autoplay: { running: false, paused: false, pause: [Function], run: [Function], start: [Function], stop: [Function] }

It seem swiper as load my configuration correctly but wont start the autoplay.

Hope someone can understand why and help this thread šŸ™.

ā€”ā€” Code ā€”ā€”

I added SwiperModule in imports of my NgModule (home.module.ts).

home.page.ts

import { Component, OnInit } from '@angular/core';
import Swiper, { Autoplay } from 'swiper';
import { IonicSlides } from '@ionic/angular';

SwiperCore.use([ Autoplay, IonicSlides ]);

@Component({
  selector: 'app-home',
  templateUrl: './home.page.html',
  styleUrls: [ './home.page.scss' ]
})
export class HomePage implements OnInit {

  swiperConfig = {
    slidesPerView: 1,
    spaceBetween: 0,
    autoplay: {
      delay: 1000
    }
  }

  constructor() {}
  ngOnInit() {}
}

home.page.html

<ion-content [fullscreen]="true">
  <swiper direction="horizontal" [config]="swiperConfig">
    <ng-template swiperSlide>Slide 1</ng-template>
    <ng-template swiperSlide>Slide 2</ng-template>
    <ng-template swiperSlide>Slide 3</ng-template>
    <ng-template swiperSlide>Slide 4</ng-template>
  </swiper>
</ion-content>

home.page.scss is empty


Solution

  • For my Ionic 6 / Angular project, I needed to obtain a reference to the Swiper and then set the "running" property to true for it to actually start moving.

    I.e. in your component HTML:

    <swiper ... other properties ... #swiperComponent>
    

    In your page.ts obtain the reference to that component:

    @ViewChild('swiperComponent') swiperComponent: SwiperComponent;
    

    And then:

    ngAfterViewInit() {
       this.swiperComponent.swiperRef.autoplay.running = true;
    }
    

    Bit of a hack but it fixed it for me.