Tuesday, January 7, 2020

Angular 8/9 Responsive Carousel Examples

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

Implementing Responsive Carousel in Angular

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.
Angular 8/9 Responsive Carousel Examples

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