Search code examples
javascriptangulartypescriptcdnswiper.js

How to use Swiperjs CDN in Angular?


I understand there is a module, but I would like to use Swiper js in my angular app through its CDN.

I have included the scripts in head of my index.html.

Then in the component where I want to use it, I have delared it as such:

import { Component, OnInit } from '@angular/core';
import { MenuService } from '../_services/menu.service';
import { ContentfulService } from '../_services/contentful.service';
import { Entry } from 'contentful';
declare let Swiper: any;

/* and initialised in the constructor*/

  constructor(
    public menu: MenuService,
    private contentfulService: ContentfulService
  ) {
    new Swiper('.swiper-container', {
      // Optional parameters
      direction: 'vertical',
      loop: true,
    });
  }

I am not getting any errors, but it simply will not work. The arrows for instance are also loaded but there is no event bound to them. Any help is much appreciated.


Solution

  • Just change your script and css link in index.html https://stackblitz.com/edit/angular-d21ywf

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Swiper/3.4.2/css/swiper.min.css">
      <script src="https://cdnjs.cloudflare.com/ajax/libs/Swiper/3.4.2/js/swiper.min.js"></script>
    

    and take your swiper to afterinit

    import { Component ,AfterViewInit} from '@angular/core';
    declare let Swiper: any;
    
    
    @Component({
      selector: 'my-app',
      templateUrl: './app.component.html',
      styleUrls: [ './app.component.css' ]
    })
    export class AppComponent  implements AfterViewInit {
      name = 'Angular';
    
      constructor() {
    
      }
      ngAfterViewInit() {
        new Swiper('.swiper-container', {
           pagination: '.swiper-pagination',
            paginationClickable: true,
            nextButton: '.swiper-button-next',
            prevButton: '.swiper-button-prev',
            autoplay: 3000,
            spaceBetween: 30,
            direction: 'vertical',
            loop: true
        });
      }
    }