Angular 13/12 Swiper Slider Example using ngx-useful-swiper

The Swiper Slider implementation tutorial using the ngx-useful-swiper package in the latest Angular version.   Swiper Slider Carousel is actually more than an Image Slider, we can have any type of content from HTML, graphics, video etc. Swiper also supports parallax effect multiple slide effects, having verticle and horizontal sliders. It also supports nested and…

By.

min read

The Swiper Slider implementation tutorial using the ngx-useful-swiper package in the latest Angular version.  

Swiper Slider Carousel is actually more than an Image Slider, we can have any type of content from HTML, graphics, video etc. Swiper also supports parallax effect multiple slide effects, having verticle and horizontal sliders. It also supports nested and easy installation of multiple Sliders/ Carousels on a single view.

Image or HTML content sliders add are used for many purposes for users to display a number of items in a limited space like Amazone show items to buy and some websites or application displays offer sliders on the home page.

Swiper sliders are fully responsive and compatible with touch devices as well. Adapt to any screen size with options to configure a number of slides to show on each screen size. We will look into all these features in this tutorial.

In this article, we will implement the Swiper slider/ carousel in Angular application and will look into its features and configurational options by simple examples.

You can continue the installation steps in your current project or create a new one using Ng CLI tool by running the following command:

$ ng new swiper-demo
? Would you like to add Angular routing? Yes
? Which stylesheet format would you like to use? SCSS

Let’s get started!

Step 1) Install Swiper Slider packages

Run the following NPM commands one by one to install the ngx-useful-swiper package and also its type @types/swiper as we are using the JS library.

npm install --save ngx-useful-swiper@latest swiper
npm install --save-dev @types/swiper

 

Step 2) Add Swiper style

Swiper slider is created by using some basic styling which we need to add in the project. We need to open the  angular.json file and append swiper.css under "styles" property as shown below:

....
  "styles": [
    "src/styles.scss",
    "./node_modules/swiper/css/swiper.css"
  ],
....

Step 3) Update App Module

To use Swiper slider in a component, we need to import the NgxUsefulSwiperModule from 'ngx-useful-swiper' then add in the imports array as shown below:

// app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

import { NgxUsefulSwiperModule } from 'ngx-useful-swiper';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    NgxUsefulSwiperModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

That’s it we are done with the installation and configuration part to use Swiper slider in the Angular project.

Use Basic Swiper Slider in the Component

To demonstrate how simple is adding a Swiper slider, just follow these steps to add a most basic Slider in a component.

In the component template add following HTML content to add a Swiper slider:

<swiper [config]="config">

  <div class="swiper-wrapper">

    <div class="swiper-slide" *ngFor="let slide of slideData">
      <img src="https://i.picsum.photos/id/{{slide.id}}/400/300.jpg" />
      {{slide.name}}
    </div>

  </div>

  <!-- Add Pagination -->
  <div class="swiper-pagination"></div>

  <!-- Add Arrows -->
  <div class="swiper-button-next"></div>
  <div class="swiper-button-prev"></div>

</swiper>

In the above code, we have <swiper>component directive with an input property [config] to provider configuration object.

Slides to show are wrapped in a div with class ‘swiper-wrapper’. We are creating slides using Angular’s *ngFor directive to iterate over slidesDate with id and name properties.

There are also containers for pagination Dots and Next, Previous arrows.

 

Next, update the component class with the following code:

// app.component.ts
import { Component } from '@angular/core';
import { SwiperOptions } from 'swiper';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  title = 'ng-swiper-demo';

  slideData = [
    {
      id: 382,
      name: "Metal bluetooth cyan",
    }, {
      id: 822,
      name: "Avon",
    }, {
      id: 159,
      name: "Infrastructures",
    }, {
      id: 424,
      name: "Users Cotton",
    }, {
      id: 572,
      name: "Haptic Oklahoma Jewelery",
    }, {
      id: 127,
      name: "Circles Integration Street",
    }, {
      id: 1009,
      name: "uniform Communications Tuna",
    }, {
      id: 619,
      name: "North Carolina",
    }, {
      id: 716,
      name: "Eyeballs Rubber",
    }, {
      id: 382,
      name: "Nevada green unleash",
    }
  ]

  config: SwiperOptions = {
    pagination: { el: '.swiper-pagination', clickable: true },
    autoHeight: true,
    allowTouchMove: true,
    autoplay: {
      delay: 6000,
      disableOnInteraction: true
    },
    breakpoints: {
      1024: {
        slidesPerView: 4
      },
      500: {
        slidesPerView: 3
      },
      400: {
        slidesPerView: 2
      },
      300: {
        slidesPerView: 1
      }
    },
    navigation: {
      nextEl: '.swiper-button-next',
      prevEl: '.swiper-button-prev'
    },
    loop: true
  };
}

The SwiperOptions type provides the properties to configure the slider.

Configuration Options

Let’s have a look on some cool configurations available in Swiper slider:

breakpoints: This option takes screen size up to which we can control slider configuration. For example in the above object for screen size 400 number of slidesPerView should be 2.

autoplay: The autoplay property enables auto sliding of slides after some delay value.

navigation: Navigation arrows can be customized by adding custom classes for nextEl and prevEl properties.

initialSlide: Index number of the initial slide.
<strong>direction</strong>: Could be 'horizontal' or 'vertical' (for vertical slider).
speed: Duration of transition between slides (in ms)

effect: Transition effect. Could be “slide”, “fade”, “cube”, “coverflow” or “flip”

spaceBetween: Distance between slides in px.

centeredSlides: If true, then the active slide will be centered, not always on the left side.

grabCursor: Grab Cursor

Methods to Control Slider

Using the template variable we can get slider instances that can be used to get Slider properties for example Active Slide’s Index.

In the slider element set template variable <strong>#usefulSwiper</strong>

<swiper [config]="config" #usefulSwiper>
  <div class="swiper-wrapper">
    <div class="swiper-slide" *ngFor="let slide of slideData">
      <img src="https://i.picsum.photos/id/{{slide.id}}/400/300.jpg" />
      {{slide.name}}
    </div>
  </div>
  <!-- Add Pagination -->
  <div class="swiper-pagination"></div>
  <!-- Add Arrows -->
  <div class="swiper-button-next"></div>
  <div class="swiper-button-prev"></div>
</swiper>

 

Now in component class, we need to import

...
import { SwiperComponent } from 'ngx-useful-swiper';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  title = 'ng-swiper-demo';

  @ViewChild('usefulSwiper', { static: false }) usefulSwiper: SwiperComponent;


  //Methods

  nextSlide() {
    this.usefulSwiper.swiper.slideNext();
  }

  previousSlide() {
    this.usefulSwiper.swiper.slidePrev();
  }
  
  slideToThis(index) {
    this.usefulSwiper.swiper.slideTo(index);
  }

...

 

To control slider just button with click events to move next, prev or to a specific slide index.

<button (click)="nextSlide()">Next Slide</button>

<button (click)="previousSlide()">Previous Slide</button>

<button (click)="slideToThis(4)">Move to Slide 4</button>

 

Binding Events on Swiper Slider

To bind events we use on the property in the configuration:

config: SwiperOptions = {

    ...
    ...

    on: {
      slideChange: () => {
        console.log('slideChange Event: Active Slide Index = ', this.usefulSwiper.swiper.activeIndex);

      },
      slideChangeTransitionEnd: () => {
        console.log('slideChange Event');
      }
    }
  };

In the next article, we will get to know How to add an animation effect to slides in the Swiper carousel.

5 responses to “Angular 13/12 Swiper Slider Example using ngx-useful-swiper”

  1. roodolphe Avatar
    roodolphe

    Thank for this tutorials .. it was useful to me ..

  2. arek Avatar
    arek

    Thanks for this tutorial, its great. I have only one issue on prod. There is error:
    l.children is not a function

    1. arek Avatar
      arek

      I am using angular 10

Leave a Reply

Your email address will not be published. Required fields are marked *