Swiper not working in an Angular Ionic app

Discussão em 'Angular' iniciado por Michael Maurel, Setembro 11, 2024.

  1. So i'm trying to implement a slider in an angular application. I stumble upon SwiperJS which seems to do everything I need. The first implementation works and I'm able to slide between images, but I also need sometimes to scroll to an image of the slider, and this does not work.

    I'm using Swiper 9.4.1

    It's registered in the AppComponent via this import:

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


    In the global.scss file

    @import 'swiper/swiper-bundle.css';


    Then I added the custom elements in my page's module

    import { CUSTOM_ELEMENTS_SCHEMA, NgModule } from '@angular/core';
    @NgModule({
    ...
    schemas: [CUSTOM_ELEMENTS_SCHEMA],
    })
    export class ProductInfoPageModule {}


    In my template, I added the swiper like this:

    <swiper-container class="swiperContainer" #swiperContainer>
    <swiper-slide *ngFor="let img of selectedArticle.media_gallery">
    <img [src]="img | mainPhoto : product.brand" alt="'img'" />
    </pinch-zoom>
    </swiper-slide>
    </swiper-container>


    Finally, in the page I initialised it with a initSwiper() function, called after all the data have been collected:

    @ViewChild('mainGrid') mainGrid: ElementRef;
    @ViewChild('swiperContainer', { static: true }) swiperContainer: ElementRef;
    [...]
    public initSwiper(): void {
    this.swiper = new Swiper('.swiperContainer', {
    cssMode: true,
    speed: 400
    });
    }


    When the user click in the page, I want to be able to scroll the Swiper to the corresponding image:

    public onThumbnailClick(index: number): void {
    this.thumbnailIndex = index;
    this.swiper.slideTo(index);
    }


    But when the code runs, it fires this error from the Swiper library: Cannot read properties of undefined (reading 'scrollTo') at Swiper.slideTo (slideTo.js:112:17)

    The code that fires this error is here:

    wrapperEl.scrollTo()


    It looks like the "wrapperEl" is never initialized How can I correct this?

    Continue reading...

Compartilhe esta Página