Angular 16 Bootstrap Responsive Carousel Tutorial

Last Updated on by in Angular
A comprehensive step by step tutorial on building responsive Carousel in Angular 16 application using Bootstrap framework and npm 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 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

Let’s get started.

Setting Up Angular Project

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

npm install -g @angular/cli@latest

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

Configure Carousel Package in Angular

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

npm install 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, you have to ensure that you add the @angular/localize package in angular, therefore install.

npm install @angular/localize

Then, import ‘@angular/localize/init’ in your polyfills.ts file.

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 { AppComponent } from './app.component';

import { NgbModule } from '@ng-bootstrap/ng-bootstrap';

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

export class AppModule {}

Implementing Responsive Carousel in Angular 13

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

Adding Animation to NgBootstrap 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;
}

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.

<div class="container mt-5">
  <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>
</div>

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.

<div class="container mt-5">
  <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>
</div>

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.scss']
})

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

Manage Carousel Behavior with NgbCarousel Methods

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.

<div class="container mt-5">
  <ngb-carousel (slide)="slideActivate($event)">
    <ng-template ngbSlide>
      <div class="picsum-img-wrapper">
        <img src="https://picsum.photos/200/300" 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="https://picsum.photos/200/300" 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>
</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.scss'],
})
export class AppComponent implements OnInit {
  @ViewChild('ngcarousel', { static: true }) ngCarousel!: NgbCarousel;

  ngOnInit() {}

  // Move to specific slide
  navigateToSlide(item: any) {
    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();
  }
}

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

ng serve --open

Conclusion

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