Angular 8/9 Responsive Image Carousel Using Ng-Bootstrap Tutorial By Example

Angular responsive image carousel implementation tutorial using the ng-bootstrap tutorial version 8 and 9

There are a number of options available for an Image/ Content Carousel in Angular project, but Bootstrap Carousels are pretty much popular among developers due to their easy implementation and very fewer dependencies.

In this tutorial, we will discuss how to implement Bootstrap Carousel in Angular project using ng-bootstrap package. NgBootstrap is built on Angular with readily available UI components, which is very easy to install and usage of UI components is very smooth.

Those who are new to ng-bootstrap, we will start from scratch. First, we will create a new Angular project using latest NgCLI version 8.3.0 and then install the ng-bootstrap package with latest version 4.3.1.

Let’s start!

Create a new Angular project

Here we will use Ng CLI tool to create a new Angular project, run following command in terminal:

$ ng new ng-bootstrap-carousel-demo</pre>
<h3>Install Bootstrap in Angular Project</h3>
Let's install Bootstrap by running following NPM command. This will install the latest bootstrap version ( Current is 4.3.1 )
<pre class="wp-block-prismatic-blocks"><code class="language-javascript">$ npm install --save @ng-bootstrap/ng-bootstrap</pre>
ng-bootstrap includes UI components only, so for adding styling to these components we need to include CSS styling file in the<strong> index.html</strong> at Angular project root
<pre class="wp-block-prismatic-blocks"><code class="language-javascript">  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" ></pre>
 

Import <code>NgbModule ( Bootstrap module ) & FormsModule ( for Angular as we will use [(ngModel)] ) in the app.module.ts file
// 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 { NgbModule } from '@ng-bootstrap/ng-bootstrap';

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

Add Bootstrap Carousel

Now we have successfully installed and configured ng-bootstrap in our Angular project.

To use ng-bootstrap Carousel we use ngb-carousel directive with some properties which we will discuss later. The ngb-carousel works as a container for Carousel slides.

For each slide, in our carousel, we add an ng-template element with ngbSlide directive. Each ng-template element with ngbSlide acts as a carousel slide.

<ngb-carousel>
    <ng-template ngbSlide>
        <div class="picsum-img-wrapper">
            <img src="./image1.jpg" alt="Random first slide">
        </div>
        <div class="carousel-caption">
            <h3>First slide label</h3>
            <p>Nulla vitae elit libero, a pharetra augue mollis interdum.</p>
        </div>
    </ng-template>
    <ng-template ngbSlide>
        ...
        ...
    </ng-template>
    <ng-template ngbSlide>
        ...
        ...
    </ng-template>
</ngb-carousel></pre>
 

There are some important option properties available which we will discuss now.
<h4>NgbCarousel</h4>
<em>Input Properties:</em>

<strong>activeId</strong>: The id of a slide which we want to display initially.

<strong>interval</strong>: Time in ms after which slide moves to next.

<strong>keyboard</strong>: To enable/ disable keyboard interaction, default is set to true.

<strong>pauseOnHover</strong>: Default is set to true, the carousel will stop on mouse hovers.

<strong>showNavigationArrows</strong>: Next and Previous arrow controls can be controlled by providing boolean value. Default is set to true.

<strong>showNavigationIndicators</strong>: Bottom indicators are controlled using this property. Default is set to true.

<strong>wrap</strong>: Property to loop over slides, default is set to true and show the first slide after last.
<pre class="lang:xhtml mark:2-8 decode:true"><ngb-carousel
[showNavigationArrows]="true" 
[showNavigationIndicators]="true"
interval="10000"
[keyboard]="true"
[pauseOnHover]="true"
[wrap]="true"
[activeId]="'slideTwo'"
>
    <ng-template ngbSlide id="slideOne">
        <div class="picsum-img-wrapper">
            <img [src]="images[0]" alt="Random first slide">
        </div>
        <div class="carousel-caption">
            <h3>First slide label</h3>
            <p>Nulla vitae elit libero, a pharetra augue mollis interdum.</p>
        </div>
    </ng-template>
    <ng-template ngbSlide id="slideTwo">
        <div class="picsum-img-wrapper">
            <img [src]="images[1]" alt="Random second slide">
        </div>
        <div class="carousel-caption">
            <h3>Second slide label</h3>
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
        </div>
    </ng-template>
    <ng-template ngbSlide id="slideThree">
        <div class="picsum-img-wrapper">
            <img [src]="images[2]" alt="Random third slide">
        </div>
        <div class="carousel-caption">
            <h3>Third slide label</h3>
            <p>Praesent commodo cursus magna, vel scelerisque nisl consectetur.</p>
        </div>
    </ng-template>
</ngb-carousel></pre>
 

<em>Output Properties:</em>

<strong>slide</strong>: An event emitted right after the slide transition is completed.
<pre class="lang:js mark:2 decode:true"><ngb-carousel
(slide)="onSlide($event)"
>
...
...
...
</ngb-carousel></pre>
In component, we will import <code>NgbSlideEvent & NgbSlideEventSource then use the slide method as shown below:
import { Component, OnInit, ViewChild } from '@angular/core';
import { NgbSlideEvent, NgbSlideEventSource } from '@ng-bootstrap/ng-bootstrap';

@Component({
  selector: 'app-carousel',
  templateUrl: './carousel.component.html',
  styleUrls: ['./carousel.component.css']
})
export class CarouselComponent implements OnInit {
...
...
  constructor() { }

  ngOnInit() {
  }

  onSlide(slideEvent: NgbSlideEvent) {
    console.log(slideEvent.source);
    console.log(NgbSlideEventSource.ARROW_LEFT);
    console.log(slideEvent.paused);
    console.log(NgbSlideEventSource.INDICATOR);
    console.log(NgbSlideEventSource.ARROW_RIGHT);
  }
...
...

}

 

Carousel behavior can be controlled from outside using the below methods:

Methods:

select: Navigates to a slide with provided slide id.

prev: Navigates to the previous slide.

next: Navigates to the next slide.

pause: Pauses the navigation of slides.

cycle: Restarts the slides navigation from left to right.

To use above methods on a carousel we add a template reference variable #mycraousel and call above methods from the component as shown below:

<ngb-carousel
#mycarousel
...
...
>
...
...
</ngb-carousel>

<button (click)="goToSlide('slideThree')">Pause</button>
<button (click)="pauseCarousel()">Play</button>
<button (click)="moveNext()">Next</button>
<button (click)="getPrev()">Prev</button>
<button (click)="goToSlide('slideThree')">Move to Slide Three</button>

In component use @ViewChild to get carousel reference then import NgbCarousel as shown below:

import { Component, OnInit, ViewChild } from '@angular/core';
import { NgbSlideEvent, NgbSlideEventSource, NgbCarousel } from '@ng-bootstrap/ng-bootstrap';

@Component({
  selector: 'app-carousel',
  templateUrl: './carousel.component.html',
  styleUrls: ['./carousel.component.css']
})
export class CarouselComponent implements OnInit {
  images = [1, 2, 3].map(() => `https://picsum.photos/900/500?random&t=${Math.random()}`);
  showNavigationArrows = true;
  showNavigationIndicators = true;
  pauseOnHover = true;

  @ViewChild('mycarousel', {static : true}) carousel: NgbCarousel;

  constructor() { }

  ngOnInit() {
  }

  ...
  ...

  startCarousel() {
    this.carousel.cycle();
  }

  pauseCarousel() {
    this.carousel.pause();
  }

  moveNext() {
    this.carousel.next();
  }

  getPrev() {
    this.carousel.prev();
  }

  goToSlide(slide) {
    this.carousel.select(slide);
  }

}

So in this post, we discussed how to use Bootstrap Carousel in Angular project with content and images. There is a demonstration on Bootstrap carousel with available input and output properties and events using which we can control Carousel navigation from a component using a reference variable.

Check other NgBootstrap tutorials here.

5 thoughts on “Angular 8/9 Responsive Image Carousel Using Ng-Bootstrap Tutorial By Example”

  1. Miguel Figueroa

    Thank you very much, the tutorial worked perfectly for me. No inconvenience when doing it step by step. Greetings from Chile.

Leave a Comment

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