Adding SwiperJS Sliders To An Angular Project With A Custom Config
Tags: angular, webdev, css, frontend
Published: 2023-10-18 13:45:19


## A Guide to Setting up SwiperJS


Those who are familiar with [SwiperJS](https://swiperjs.com/) 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](https://swiperjs.com/angular) from the project in favor of [web components](https://developer.mozilla.org/en-US/docs/Web/API/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
```

---

## Setting up the Swiper Directive & Module


Next, we want to create a [Directive](https://angular.io/api/core/Directive) for our Swiper. In your project create a directives folder if you don’t already have one.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/05xb7xdhnb6baxp4zoa3.png)


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


```javascript
    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();
      }
    }
```

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vd6cb52biuzvp55d3qbt.png)


Declare and Export the `SwiperDirective`

```javascript
    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 {}
```

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.

```javascript
    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 {
    
    }
```

---

## 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 `ViewChild `from `@angular/core` along with `Swiper` and `SwiperOptions` from `swiper`.

```javascript 
   import { Component, ElementRef, ViewChild } from '@angular/core';
    import { Swiper, SwiperOptions } from 'swiper';
```

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

```javascript
    @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
        }
      }
    }
```

---

## Setting up the Swiper HTML

Add `swiper-container `and `swiper-slide` elements to your template.

```html
    <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>
```

`#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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o04vlfr4r17fjy0xj2q0.png)


---

## Customizing the Scrollbar

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

```javascript
        scrollbar: {
          el: '.swiper-scrollbar',
          enabled: true,
          draggable: true
        }
```

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

      

```
<div class="swiper-scrollbar"></div>
```

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:

```css
    section {
      width: 90%;
      margin: auto;
      position: relative
    }
```

Now we will position the scrollbar absolutely:

```css
    :host ::ng-deep .swiper-scrollbar{
      position: absolute;
      bottom: -2rem;
    }
```

Give the scrollbar a custom height:

```css
    :host ::ng-deep .swiper-scrollbar.swiper-scrollbar-horizontal {
      height: .65rem;
    }
```

…and style the bar itself:

```css
    :host ::ng-deep .swiper-scrollbar.swiper-scrollbar-horizontal .swiper-scrollbar-drag{
      background: navy;
      height: .5rem;
      padding: .1rem;
    }
```

_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/](https://www.joshuacolvin.net/understanding-ng-deep/)_


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/evf1az55b6h69bpjhcft.png)


---

## Customizing the Navigation

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

```javascript
        navigation: {
          nextEl: '.swiper-button-next',
          prevEl: '.swiper-button-prev',
        },
```

…and add these elements to the template:

```html
    <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>
```

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5lzyrp0xeqzcjm9akap0.png)


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

```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;
      }
    }
```

---

## 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](https://github.com/soldierforus/swiperJS-tutorial)