Building Responsive Carousel in Angular 9 Application with NgBootstrap

Building Responsive Carousel in Angular 9 Application with NgBootstrap

In this Angular 9 tutorial, you'll learn step by step tutorial on building Responsive Carousel in Angular 9 Application with NgBootstrap package. Angular 8/9 Responsive Carousel tutorial with examples. Carousels are used on the front of the web or mobile applications, Carousels are cool and helpful in displaying image galleries, sell products, show related content, showing repetitive content, attract the attention of new visitors

A comprehensive step by step tutorial on building responsive Carousel in Angular 9 application with NgBootstrap package.

Carousels are used on the front of the web or mobile applications, Carousels are cool and helpful in displaying image galleries, sell products, show related content, showing repetitive content, attract the attention of new visitors

There are multiple Angular Carousel packages available online to display the repetitive data on the front-end to the visitors.

In this tutorial, we will learn how to integrate responsive Bootstrap carousel in an Angular 8|9 application using the ng-bootstrap library.

NgBootstrap comes with built-in carousel exclusively for Angular, and this ready-made carousel is extremely simple to install and allow easy implementation of the following features.

  • Auto Rotate
  • Arrow navigation
  • Dynamic pagination
  • Rotating animations
  • Various slides with images and text

Table of Contents

  1. Setting Up Angular Project
  2. Configure Carousel Package in Angular
  3. Implementing Carousel in Angular 8/9
  4. Adding Animation to NgBootstrap Carousel
  5. Understanding NgbCarousel Methods
  6. Manage Carousel Behavior with NgbCarousel Methods
  7. Conclusion

Let’s get started.

1. Setting Up Angular Project

Make sure you have the latest version of Angular CLI installed on your device.

npm install -g @angular/[email protected]

If it throws any error then use the above command with sudo and provide admin password.

Use Angular CLI to generate a new Angular app, enter the command in the terminal and hit enter.

ng new angular-bootstrap-carousel

Get inside the project folder.

cd angular-bootstrap-carousel

To configure the NgBootstrap library we need to install Bootstrap library. Because NgBootstrap is just a UI component library for Bootstrap.

npm install --save @ng-bootstrap/ng-bootstrap

Next, we will install the ng-bootstrap module to configure the carousel in an Angular app.

npm install --save @ng-bootstrap/ng-bootstrap

Now, add the Bootstrap CSS in styles:[] array inside the angular.json file.

"styles": [
  "node_modules/bootstrap/dist/css/bootstrap.min.css"
]

Next, we will import NgbModule in main module file and also register NgbModule inside the imports array in app.module.ts file.

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

We have completed the configuration process. Next, run the app in the browser by running the following command.

ng serve --open

To begin with ng-bootstrap Carousel, we define ngb-crousel directive.

To display every slide we use the ng-template directive and attach ngbSlide attribute with it. It acts as an individual slide in the Angular template.

To run the carousel, keep some images in the assets folder.

<ngb-carousel>
  <ng-template ngbSlide>
    <div class="picsum-img-wrapper">
      <img src="assets/img-01.jpeg" alt="Angular Carousel 1">
    </div>
    <div class="carousel-caption">
      <h3>Title Goes Here</h3>
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
    </div>
  </ng-template>
  <ng-template ngbSlide>
    <div class="picsum-img-wrapper">
      <img src="assets/img-02.jpeg" alt="Angular Carousel 2">
    </div>
    <div class="carousel-caption">
      <h3>Title Goes Here</h3>
      <p>Consectetur tortor volutpat pretium.</p>
    </div>
  </ng-template>
</ngb-carousel>

Angular Responsive Carousel

NgBootstrap does not provide any official API for animating bootstrap carousel, however there are two ways through which we can add animation in Angular carousel. First, method is using Angular animation. Other method is by using CSS 3 animation, we are going to focus on the CSS method in this tutorial.

Add the following CSS in the styles.css file and it will add the animated fade-in effect in the Angular Carousel.

ngb-carousel {
    max-width: 700px;
    margin: 50px auto;
}

ngb-carousel img {
    width: 100%;
    outline: none;
}

ngb-carousel {
    width: inherit;
    height: inherit;
}

.carousel-inner {
    overflow: visible;
}

.carousel-item {
    display: flex !important;
    opacity: 0;
    visibility: hidden;
    transition: opacity 1.2s ease-in-out, visibility 1.2s;
    z-index: -1;
}

.carousel-item.active{
    opacity: 1;
    visibility: visible;
    z-index: 10;
}

.carousel-control-prev {
     z-index: 20;
}

.carousel-control-next {
     z-index: 20;
}

.carousel-indicators{
    z-index: 20;
}

5. Understanding NgbCarousel Methods

NgbCarousel is a component provided by NgBootstrap, and It helps in handling the setting of a Carousel in Angular. Below we will have a look at NgBootstrap’s Inputs, Outputs and Methods properties to deal with Bootstrap carousel.

NgbCarousel Inputs API

activeId: The slide id, which appears at the beginning.

interval: The time in milliseconds, within the duration slide goes to next.

Keyboard: The initial value is true, used to configure communication through the keyboard.

pauseOnHover: To stop carousel on when the mouse comes over the slides. The default value is true.

showNavigationArrows: If enable Next and Previous control arrows will be visible. However, the default is always true.

showNavigationIndicators: If the value is true Bottom indicators will be apparent if the value is set to true. However, the default value is true.

wrap: If the value is set to true, then the wrap property switches the last slide back to the first. However, the default value is true.

<ngb-carousel
[showNavigationArrows]="true" 
[showNavigationIndicators]="true"
interval="12000"
[keyboard]="true"
[pauseOnHover]="true"
[wrap]="true"
[activeId]="'secondSlide'"
>
  <ng-template ngbSlide id="firstSlide">
    <div class="picsum-img-wrapper">
      <img src="assets/img-01.jpeg" alt="Angular Carousel 1">
    </div>
    <div class="carousel-caption">
      <h3>Title Goes Here</h3>
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
    </div>
  </ng-template>
  <ng-template ngbSlide id="secondSlide">
    <div class="picsum-img-wrapper">
      <img src="assets/img-02.jpeg" alt="Angular Carousel 2">
    </div>
    <div class="carousel-caption">
      <h3>Title Goes Here</h3>
      <p>Consectetur tortor volutpat pretium.</p>
    </div>
  </ng-template>
</ngb-carousel>

Using Outputs API

slide: This event is triggered just after the slide transition is finished.

Define the (slide)="..." event with ngb-carousel directive in the Angular’s HTML template.

<ngb-carousel (slide)="slideActivate($event)">
  <ng-template ngbSlide>
    <div class="picsum-img-wrapper">
      <img src="assets/img-01.jpeg" alt="Angular Carousel 1">
    </div>
    <div class="carousel-caption">
      <h3>Title Goes Here</h3>
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
    </div>
  </ng-template>
  <ng-template ngbSlide>
    <div class="picsum-img-wrapper">
      <img src="assets/img-02.jpeg" alt="Angular Carousel 2">
    </div>
    <div class="carousel-caption">
      <h3>Title Goes Here</h3>
      <p>Consectetur tortor volutpat pretium.</p>
    </div>
  </ng-template>
</ngb-carousel>

Next, we require to import NgbSlideEvent and NgbSlideEventSource in app.component.ts. Afterwards, use the slide function to access the following events triggered by the following properties.

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  slideActivate(ngbSlideEvent: NgbSlideEvent) {
    console.log(ngbSlideEvent.source);
    console.log(ngbSlideEvent.paused);
    console.log(NgbSlideEventSource.INDICATOR);
    console.log(NgbSlideEventSource.ARROW_LEFT);
    console.log(NgbSlideEventSource.ARROW_RIGHT);
  }
}

To handle Bootstrap Carousel behavior in Angular we use the following method offered by NgbCarousel.

select: Moves to a slide with provided slide id.

prev: Moves to the previous slide.

next: Navigates to the next slide.

pause: Stops the navigation of carousel slides.

cycle: Restarts the sliding from left to right in the carousel.

Next, we will learn how to use these output methods to ad the external events in the Angular Carousel.

Declare a template reference and bind it to the ngb-carousel and trigger the following method.

<ngb-carousel #ngcarousel>
  <ng-template ngbSlide id="one">
    <div class="picsum-img-wrapper">
      <img src="assets/img-01.jpeg" alt="Slide 1">
    </div>
  </ng-template>
  <ng-template ngbSlide id="two">
    <div class="picsum-img-wrapper">
      <img src="assets/img-02.jpeg" alt="Slide 2">
    </div>
  </ng-template>
  <ng-template ngbSlide id="three">
    <div class="picsum-img-wrapper">
      <img src="assets/img-03.jpeg" alt="Slide 3">
    </div>
  </ng-template>
  <ng-template ngbSlide id="four">
    <div class="picsum-img-wrapper">
      <img src="assets/img-04.jpeg" alt="Slide 4">
    </div>
  </ng-template>
</ngb-carousel>

<div class="text-center">
  <button (click)="navigateToSlide('four')">Go to Slide Four</button>
  <button (click)="getToPrev()">Prev</button>
  <button (click)="goToNext()">Next</button>
  <button (click)="stopCarousel()">Pause</button>
</div>

Next, trigger the Output methods in the Angular component.

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent implements OnInit {
  @ViewChild('ngcarousel', { static: true }) ngCarousel: NgbCarousel;

  ngOnInit() { }

  // Move to specific slide
  navigateToSlide(item) {
    this.ngCarousel.select(item);
    console.log(item)
  }

  // Move to previous slide
  getToPrev() {
    this.ngCarousel.prev();
  }

  // Move to next slide
  goToNext() {
    this.ngCarousel.next();
  }

  // Pause slide
  stopCarousel() {
    this.ngCarousel.pause();
  }

  // Restart carousel
  restartCarousel() {
    this.ngCarousel.cycle();
  }
}

7. Conclusion

Finally, we have completed Angular 8/9 Responsive Carousel tutorial with examples. I hope you liked this tutorial, please consider it sharing with others.

Angular 9 Tutorial: Learn to Build a CRUD Angular App Quickly

What's new in Bootstrap 5 and when Bootstrap 5 release date?

Brave, Chrome, Firefox, Opera or Edge: Which is Better and Faster?

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

Angular Bootstrap Tutorial - Building Websites with Angular Bootstrap

In this Angular Bootstrap tutoria will help you learn to create beautiful websites easily using Bootstrap along with Angular. You'll learn: What is Angular? What is Bootstrap? Creating an Angular Application; Embedding Bootstrap with Angular

How to create Angular 9 Form with Template Driven Form using Bootstrap

In this Angular 9 Form tutorial, we are going to learn how to implement simple validation rules with the template-driven approach using Bootstrap forms. Learn how to implement Bootstrap in Angular 9 and create forms with Bootstrap. Learn how to work with the ngModel directive to handle the Angular form data.

How to Add Bootstrap in Angular 9

In this Angular 9 tutorial, I'm going to explain you example of how to install Bootstrap in Angular 9. We will help you to give example of how to add Bootstrap 4 in Angular 9. You can see how to use Bootstrap in Angular 9. You can understand a concept of Angular 9 install Bootstrap 4. You just need to some step to done Angular 9 add Bootstrap 4.