Ionic 7 Swiper 11: How to set the parameter in Typescript?

381 views Asked by At

I have my codes below. I wanted to set the parameters of the swiper slider using a script.

<swiper-container [options]="recentPostSliderOpts" class="discover-top-banner">
  <swiper-slide *ngFor="let toplatestpost of toplatestposts">
     <!-- Some Codes Here Cut Short -->
  </swiper-slide>
</swiper-container>

Here's my code on typescript.

import { Swiper, SwiperOptions } from 'swiper/types';

recentPostSliderOpts: SwiperOptions = {
  slidesPerView: 3,
}

The [options] is not getting triggered as per the guide on Ionic Framework - https://ionicframework.com/docs/angular/slides. It worked on Swiper 9, but not on Swiper 11. I have checked the SwiperJS Official Website documentation and can't find one. I have also also tried [config] without any luck.

Can anyone help on this?

2

There are 2 answers

0
Junior Klaus Mombo-Nzahou On

To do that you will need to :

1 - create a directive for the swiper and use a template variable to keep the reference of the current swiper

<swiper-container appSwiper #swiperRef [config]="recentPostSliderOpts" class="discover-top-banner">
    <swiper-slide *ngFor="let toplatestpost of toplatestposts">
         <!-- Some Codes Here Cut Short -->
    </swiper-slide>
</swiper-container>

2 - On the ts file, you will create the config you want, and put the swiper ref in a variable so you can listen to some events.

swiper!: Swiper;
@ViewChild('swiperRef') swiperRef!: ElementRef<SwiperContainer>;

recentPostSliderOpts: SwiperOptions = {
  spaceBetween: 10,
  navigation: true,
  slidesPerView: 1.2,
}

ionViewDidEnter() {
  this.swiper = this.swiperRef?.nativeElement.swiper;

  this.swiper.on('slideChange', (swiper) => {
    console.log('slide changed:', swiper.realIndex);
  });
}

3 - Create the directive

import { AfterViewInit, Directive, ElementRef, Input } from '@angular/core';
import { SwiperContainer } from 'swiper/element';
import { SwiperOptions } from 'swiper/types';

@Directive({
  selector: '[appSwiper]',
  standalone: true
})

export class SwiperDirective implements AfterViewInit {

  @Input() config?: SwiperOptions;

  constructor(private el: ElementRef<SwiperContainer>) { }

  ngAfterViewInit(): void {
    Object.assign(this.el.nativeElement, this.config);

    this.el.nativeElement.initialize();
  }

}

4 - Then you have to add the SwiperDirective on your module imports array

5 - Add also schemas: [CUSTOM_ELEMENTS_SCHEMA] on your module to avoid some build errors

6 - Call the register function at only one place on your project. The app.module.ts is a good place

import { register } from 'swiper/element/bundle';
register();

Now it should work. Good luck !

0
Philippine LOISEAU On

This answer works, but the init="false" attribute is missing on the swiper container, otherwise the error: "Cannot read properties of null (reading 'remove')" appears.

https://swiperjs.com/element#virtual-slides