angularweb-componentswiper.jscustom-elementviewchild

How to use the swiper 9 pagination with Angular


I'm actually migrating to swiper 9.

I had already faced some problems and asked it here about the swiper 9 migration

Some of the answers help me moving forward. But now I'm trying to use the pagination

I used to import the pagination like follow

import SwiperCore, { Pagination, Swiper } from 'swiper'

// ...

  @ViewChild('swiperRef', { static: true })
  private _swiperRef: ElementRef | undefined
  swiper?: Swiper

// ...

  ngOnInit(): void {
    SwiperCore.use([Pagination])

    this.swiper = this._swiperRef.nativeElement.swiper
  }

But the pagination isn't working.

For what I see on their doc I should do the following

  import Swiper, { Navigation, Pagination } from 'swiper';

  const swiper = new Swiper('.swiper', {
    // configure Swiper to use modules
    modules: [Navigation, Pagination],
    ...
  });

But I do not understand, I don't have any .swiper element, and I don't which to declare any. Also, I have multiple swiper on the same page, so I would wish to target only the specific _swiperRef one.

Is it somehow in a proper way doable?


Solution

  • Quite hard to understand but I did it.

    1. Avoid the swiper initialized himself
    <swiper-container #swiperRef init="false"> 
      <!-- You slides --> 
    </swiper-container>
    
    1. You do not need to use the SwiperCore anymore
    @ViewChild('swiperRef', { static: true })
      private _swiperRef: ElementRef | undefined
    swiper?: Swiper
    
    options: SwiperOptions = {
      slidesPerView: 1,
      zoom: true,
      enabled: true,
      pagination: true,
      autoHeight: true,
    }
    
    ngOnInit() {
      const swiperEl = this._swiperRef.nativeElement
      Object.assign(swiperEl, this.options)
    
      swiperEl.initialize()
    
      this.swiper = this._swiperRef.nativeElement.swiper
    }
    
    1. Should just work out of the box