How do I add Swiper.js to an Angular project without bugs

34 Views Asked by At

I have created a Swiper.js carousel in Angular using CDN snippets into my index.html file.

The code below is what I have placed in an external js file that I call within the angular.json file.

const swiper = new Swiper(".swiper-slider", {
// Optional parameters
centeredSlides: true,
slidesPerView: 1,
grabCursor: true,
freeMode: false,
loop: true,
mousewheel: false,
keyboard: {
  enabled: true
},

// Enabled autoplay mode
autoplay: {
  delay: 5000,
  disableOnInteraction: false
},

// If we need pagination
// pagination: {
//   el: ".swiper-pagination",
//   dynamicBullets: false,
//   clickable: true
// },

// If we need navigation
navigation: {
  nextEl: ".swiper-button-next",
  prevEl: ".swiper-button-prev"
},

// Responsive breakpoints
breakpoints: {
  640: {
    slidesPerView: 1,
    spaceBetween: 20
  },
  1024: {
    slidesPerView: 1,
    spaceBetween: 20
  }
}

It works fine on page load - but if I go to one of my other pages using Routing and then go back to the page with my carousel on, the carousel stops working.

I have tried to remove the CDN links on my index.html and embed Swiper.js using npm.

I am new to Angular and have tried to import files into the Carousel component I've made but I'm not successful in any. Looking for the simplest way to install Swiper.js into my project and for it to work when using Routing for different pages.

0

There are 0 best solutions below