Developer Snippet Diary

swiper slider in angular

The Swiper is a powerful and modern touch slider which is especially advantageous for mobile interfaces. Here's a step-by-step guide to implement the Swiper slider in Angular.

1. Install Swiper: 

Firstly, you need to install Swiper into your Angular project. You can do this by using npm (node package manager). Open your terminal, navigate to your project directory and run the following command:

npm install swiper --save

2.Import Swiper styles:

Swiper comes with its own styles that need to be included in your project for it to display correctly. Open your angular.json file and add the path to Swiper's CSS in the styles array:

"styles": [
  "src/styles.css",
  "node_modules/swiper/swiper-bundle.min.css"
],

Then, you should restart your development server to apply these changes.

3.Import Swiper in your Angular component:

You need to import Swiper in the component where you want to use it. In your component TypeScript file (for example, app.component.ts), add the following lines:

export class SliderComponent implements AfterViewInit {
  images:string[] = [
    "assets/img/photos/pp10.jpg",
    "assets/img/photos/pp11.jpg",
    "assets/img/photos/pp12.jpg",
    "assets/img/photos/pp13.jpg",
    "assets/img/photos/pp14.jpg"
  ]
  ngAfterViewInit() {
    const swiper = new Swiper('.swiper-container .swiper', {
      // Optional parameters
      direction: 'horizontal',
      loop: true,
      slidesPerView: 'auto',
      spaceBetween: 30,
      touchEventsTarget: 'wrapper',
      simulateTouch: true,
      navigation: {
        nextEl: '.swiper-button-next',
        prevEl: '.swiper-button-prev',
      },
      pagination: {
        el: '.swiper-pagination',
        clickable: true // If you want the bullets to be clickable
      }

    });
  }
}

4. HTML In your component HTML file (for example, app.component.html), you can now use the Swiper HTML structure:

<section class="wrapper">
  <div class="container-fluid px-md-6">
  <div class="swiper-container blog grid-view mb-md-15" data-margin="30" data-nav="true" data-dots="true" data-items-xxl="3" data-items-md="2" data-items-xs="1">
    <div class="swiper">
      <div class="swiper-wrapper">
        <div class="swiper-slide" *ngFor="let image of images">
          <figure class="rounded"><img [src]="image" alt="" /></figure>
        </div>
      </div>
    </div>
  <div class="swiper-pagination"></div>
  <div class="swiper-scrollbar"></div>
  </div>
</div>
</section>

Now, you should have a working Swiper slider in your Angular application! Don't forget to adjust the paths of the images and the Swiper options according to your needs.

Here is official documentation: https://swiperjs.com/angular

Posted by: R GONDAL
Email: rizikmw@gmail.com