DEV Community

Cover image for Adding SwiperJS Sliders To An Angular Project With A Custom Config
Travis
Travis

Posted on • Updated on

Adding SwiperJS Sliders To An Angular Project With A Custom Config

A Guide to Setting up SwiperJS

Those who are familiar with SwiperJS know it’s a robust library for creating sliders within all frameworks. However, with the release of version 9 in February 2023 came the removal of Angular Components from the project in favor of web components. Currently, the library still offers Vue and React components, but those have been earmarked for removal in an upcoming release.

In this tutorial, we will add the latest version of SwiperJS (9.3.2 at the time of this writing) to an angular project, set up an image slider, and explore some of the features available in this rich API.


Installing SwiperJS Inside Your Angular Project

For this tutorial, I will assume you already have an angular project and are familiar with npm and the Angular CLI.

    npm install swiper
Enter fullscreen mode Exit fullscreen mode

Setting up the Swiper Directive & Module

Next, we want to create a Directive for our Swiper. In your project create a directives folder if you don’t already have one.

Image description

This is where we will create swiper.directive.ts.

    import { AfterViewInit, Directive, ElementRef, Input } from '@angular/core';
    import { SwiperOptions } from 'swiper';
    import {register} from 'swiper/element/bundle';

    register();

    @Directive({
      selector: '[swiperElement]'
    })
    export class SwiperDirective implements AfterViewInit {
      private readonly swiperElement: HTMLElement;
      @Input('config')
      config?: SwiperOptions;

      constructor(private element: ElementRef<HTMLElement>) {
        this.swiperElement = element.nativeElement;
      }

      ngAfterViewInit(): void {
        Object.assign(this.element.nativeElement, this.config)
        //@ts-ignore - We ignore this because there is no initialize method on the HTMLElement
        this.element.nativeElement.initialize();
      }
    }
Enter fullscreen mode Exit fullscreen mode

Here we are importing SwiperOptions,feeding the swiper options through the @Input(‘config’), and registering swiper.

If you are planning on using swipers throughout your project, you will want to create a module for this directive. Otherwise, you can skip this next step and declare this directive in whichever module the swiper will be used in.

Create directives.module.ts inside the directives folder.

Image description

Declare and Export the SwiperDirective

    import { NgModule } from "@angular/core";
    import { CommonModule } from "@angular/common";
    import { SwiperDirective } from "./swiper.directive";

    @NgModule({
      declarations: [SwiperDirective],
      imports: [CommonModule],
      exports: [SwiperDirective]
    })

    export class DirectivesModule {}
Enter fullscreen mode Exit fullscreen mode

Import the DirectivesModule into app.module.ts (or whichever module you will be using Swiper. Because this is a web component, we’ll also need to import CUSTOM_ELEMENTS_SCHEMA and set it up inside the schemas property array.

    import { CUSTOM_ELEMENTS_SCHEMA, NgModule } from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';

    import { AppComponent } from './app.component';
    import { DirectivesModule } from './directives/swiper.module';

    @NgModule({
      declarations: [
        AppComponent
      ],
      imports: [
        BrowserModule,
        DirectivesModule
      ],
      providers: [],
      bootstrap: [AppComponent], 
      schemas: [CUSTOM_ELEMENTS_SCHEMA]
    })
    export class AppModule {

    }
Enter fullscreen mode Exit fullscreen mode

Setting up Swiper TypeScript in the Component

Next, let’s update the app.component.ts (or whichever component you will be using swiper in) with some properties to initialize the slider. We’ll need to import ElementRef and ViewChildfrom @angular/core along with Swiper and SwiperOptions from swiper.

   import { Component, ElementRef, ViewChild } from '@angular/core';
    import { Swiper, SwiperOptions } from 'swiper';
Enter fullscreen mode Exit fullscreen mode

Inside the class we will add our swiper properties, add some dummy slides, set up our swiper config, and initialize the swiper:

    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent {
      title = 'swiper-tutorial';
      swiper?: Swiper;
      @ViewChild('swiperRef')
      swiperRef: ElementRef | undefined;
      slides: Array<{title: string}> = [
        {
          title: "Slide 1"
        },
        {
          title: "Slide 2"
        },
        {
          title: "Slide 3"
        },
        {
          title: "Slide 4"
        },
        {
          title: "Slide 5"
        },
        {
          title: "Slide 6"
        },
        {
          title: "Slide 7"
        },
        {
          title: "Slide 8"
        },
      ]

      ngAfterViewInit() {
        this.swiper = this.swiperRef?.nativeElement.swiper;
      }

      public config: SwiperOptions = {
        slidesPerView: 1,
        spaceBetween: 25,
        breakpoints: {
          320: {
            slidesPerView: 1.5,
          },
          768: {
            slidesPerView: 2.5,
          },
          1280: {
            slidesPerView: 3.5,
          }
        },
        navigation: true,
        scrollbar: {
          el: '.swiper-scrollbar',
          enabled: true,
          draggable: true
        }
      }
    }
Enter fullscreen mode Exit fullscreen mode

Setting up the Swiper HTML

Add swiper-containerand swiper-slide elements to your template.

    <section>
      <swiper-container #swiperRef swiperElement [config]="config" init="false">
        <swiper-slide *ngFor="let slide of slides" class="slide">
          <img width="300" height="200" src="https://picsum.photos/500/200" alt="randomized image">
          <h2>{{slide.title}}</h2>
          <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Necessitatibus ratione eligendi amet facere odio iste dolores perferendis corporis aperiam, tempore, id recusandae labore deleniti harum expedita illum nobis! Quo cupiditate beatae numquam velit nostrum, optio voluptates quaerat nihil incidunt.</p>
        </swiper-slide>
      </swiper-container>
      <div class="swiper-scrollbar"></div>
    </section>
Enter fullscreen mode Exit fullscreen mode

#swiperRef is what identifies this particular swiper. It will be important if you have multiple swipers with custom parts. i.e. next, prev, scrollbar.

swiperElement is defined in our swiper.directive.ts, the config is defined in our app.component.ts and init is set to false because it is initialized through the directive.

Boom! We have a working slider:

Image description


Customizing the Scrollbar

Previously we set up a custom scrollbar property in our config:

        scrollbar: {
          el: '.swiper-scrollbar',
          enabled: true,
          draggable: true
        }
Enter fullscreen mode Exit fullscreen mode

And we added the swiper-scrollbar class to a div element inside the template.

<div class="swiper-scrollbar"></div>
Enter fullscreen mode Exit fullscreen mode

Customizing scrollbars can be a bit tricky. Let’s start by positioning it absolutely under the slider. First, we will give the parent section a relative position:

    section {
      width: 90%;
      margin: auto;
      position: relative
    }
Enter fullscreen mode Exit fullscreen mode

Now we will position the scrollbar absolutely:

    :host ::ng-deep .swiper-scrollbar{
      position: absolute;
      bottom: -2rem;
    }
Enter fullscreen mode Exit fullscreen mode

Give the scrollbar a custom height:

    :host ::ng-deep .swiper-scrollbar.swiper-scrollbar-horizontal {
      height: .65rem;
    }
Enter fullscreen mode Exit fullscreen mode

…and style the bar itself:

    :host ::ng-deep .swiper-scrollbar.swiper-scrollbar-horizontal .swiper-scrollbar-drag{
      background: navy;
      height: .5rem;
      padding: .1rem;
    }
Enter fullscreen mode Exit fullscreen mode

ng-deep is the psuedo-class selector that allows us to style the scrollbar by promoting the component styles to global. You can read more about it here: https://www.joshuacolvin.net/understanding-ng-deep/

Image description


Customizing the Navigation

Update the Navigation property inside your config to include custom previous and next buttons:

        navigation: {
          nextEl: '.swiper-button-next',
          prevEl: '.swiper-button-prev',
        },
Enter fullscreen mode Exit fullscreen mode

…and add these elements to the template:

    <div class="swiper-button-prev"></div>
    <div class="swiper-button-next"></div>
    <section>
      <swiper-container #swiperRef swiperElement [config]="config" init="false">
        <swiper-slide *ngFor="let slide of slides" class="slide">
          <img width="300" height="200" src="https://picsum.photos/500/200" alt="randomized image">
          <h2>{{slide.title}}</h2>
          <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Necessitatibus ratione eligendi amet facere odio iste dolores perferendis corporis aperiam, tempore, id recusandae labore deleniti harum expedita illum nobis! Quo cupiditate beatae numquam velit nostrum, optio voluptates quaerat nihil incidunt.</p>
        </swiper-slide>
      </swiper-container>
      <div class="swiper-scrollbar"></div>
    </section>
Enter fullscreen mode Exit fullscreen mode

For this example I pulled these outside of the swiper-container. You’ll notice the buttons are now on the edges of the window as opposed to the inside of the swiper container.

Image description

We need to target these new swiper button elements and style them with css:

    /* Previous and Next buttons */

    .swiper-button-prev, .swiper-button-next {
      background-color: navy;
      color: white;
      padding: .5rem;
      border-radius: .5rem;
    }

    .swiper-button-prev {
      left: 2rem;
      right: auto;
    }

    .swiper-button-next {
      right: 2rem;
      left: auto;
    }

    @media (min-width:  640px) {
      .swiper-button-prev, .swiper-button-next {
        padding: 1rem;
      }

      .swiper-button-prev {
        left: 10rem;
      }

      .swiper-button-next {
        right: 10rem;
      }
    }
Enter fullscreen mode Exit fullscreen mode

Profit

In summation, we’ve added swiperJS to our angular project, created config settings, and set up custom styles for the scrollbar and previous/next buttons.

I hope you found this article helpful. The source for this tutorial can be found here: https://github.com/soldierforus/swiperJS-tutorial

Top comments (0)