Search code examples
angularngx-swiper-wrapper

Swiper in Angular 17


I'm diving into Angular 17 for a project and trying to integrate Swiper for a slick carousel feature. I've been scratching my head trying to get it to work but hitting a few roadblocks.

Has anyone here successfully implemented Swiper in Angular 17? I'm looking for some working example or a guide that's up to date with Angular 17's nuances.

I've tried to play with the swiper documentation to get it to function properly but to no avail.

Any help or pointers would be super appreciated!


Solution

  • import {
      AfterViewInit,
      CUSTOM_ELEMENTS_SCHEMA,
      ChangeDetectorRef,
      Component,
      ContentChild,
      ElementRef,
      Input,
      effect,
    } from '@angular/core';
    import { SwiperContainer } from 'swiper/element/bundle';
    
    @Component({
      selector: 'app-swiper',
      templateUrl: './swiper.component.html',
      styleUrl: './swiper.component.css',
      standalone: true,
      schemas: [CUSTOM_ELEMENTS_SCHEMA],
    })
    export class SwiperComponent implements AfterViewInit {
      @Input() swiperContainerId = '';
      index = 0;
      slidePerView = 1;
    
      @ContentChild('swiper') swiperRef!: ElementRef<SwiperContainer>;
      initialized = false;
    
      constructor() {}
    
      ngAfterViewInit(): void {
        setTimeout(() => {
          const shadowRoot = document
            .getElementById(this.swiperContainerId)
            ?.getElementsByClassName('swiper')[0]?.shadowRoot
            ?.firstChild as HTMLElement;
          shadowRoot.style.paddingBottom = '35px';
        }, 300);
      }
    
      changeSlide(prevOrNext: number): void {
        if (prevOrNext === -1) {
          this.swiperRef.nativeElement.swiper.slidePrev();
        } else {
          this.swiperRef.nativeElement.swiper.slideNext();
        }
      }
    }
    

    The following example works in angular 17.1 and swiper 11.0.5. It works with content projection. You can improve this code and let me know below this post and I will appreciate it.

    Stackblitz example