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
2. 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
3. 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>

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

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

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.

To validate the form, we will also look at how to use Bootstrap UI library to facilitate our form validation task. In this Angular form example, we will create a basic form with some Input fields, such as name, email, password and hobbies.

By the end of this tutorial, you will understand following things:

  • How to quickly validate a form with template-driven approach in Angular 9.
  • How to create a form with Bootstrap form template.
  • How to bind ngModel directive with input controls to set the properties on the component.
  • How to submit the form with template driven approach.

Table of Contents

  • Setting Up Angular Project
  • Importing FormsModule
  • Create Form with Bootstrap From Template
  • Implement Template-driven Form in Angular
  • Adding Validation in Template-driven Form
  • Conclusion
Setting Up Angular Project

Run the below command to generate a brand new Angular 9 project using Angular CLI.

ng new angular-template-driven-form

Head over to the Angular form project.

cd angular-template-driven-form

Install Bootstrap in Angular 9

Install Bootstrap UI framework via NPM using following command.

npm install bootstrap

Add the Bootstrap CSS path in styles array inside the angular.json file.

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

Now we have configured Angular and Bootstrap, run the command to open the app in the browser.

ng serve --open
Importing FormsModule

To get started with Form control and NgModel Angular Forms service, we require to import FormsModule in app.module.ts file.

// app/app.module.ts

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

import { FormsModule } from '@angular/forms';

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

export class AppModule { }
Create Form with Bootstrap From Template

Create a simple form in Angular using Bootstrap form component, open the app.component.html file and replace existing code with the following code.

<form novalidate>
  <div class="form-group">
    <label>Name</label>
    <input type="text" class="form-control">
  </div>

  <div class="form-group">
    <label>Email</label>
    <input type="email" class="form-control">
  </div>

  <div class="form-group">
    <label>Password</label>
    <input type="password" class="form-control">
  </div>

  <div class="form-group">
    <label>Hobbies</label>
    <select class="form-control">
      <option value="">Select an option</option>
      <option *ngFor="let hoby of Hobbies" [value]="hoby">
        {{hoby}}
      </option>
    </select>
  </div>

  <div class="form-group">
    <button class="btn btn-danger btn-block">Submit</button>
  </div>
</form>

Also, add the following options array for select drop-down input field in the app.component.ts file.

import { Component } from '@angular/core';

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

export class AppComponent {
  Hobbies: string[] = [
    'Acrobatics',
    'Acting',
    'Animation',
    'Astronomy',
    'Baking'
  ];
}
Implement Template-driven Form in Angular

Now we will add the template-driven form using ngModel directive in Angular component. Add the following code in the app.component.html file to initialize the Angular 9 template-driven form.

<form #userForm="ngForm" (ngSubmit)="onSubmit(userForm)">
  <div class="form-group">
    <label>Name</label>
    <input type="text" name="name" class="form-control" [(ngModel)]="model.name" required>
  </div>

  <div class="form-group">
    <label>Email</label>
    <input type="email" class="form-control" name="email" [(ngModel)]="model.email" required>
  </div>

  <div class="form-group">
    <label>Password</label>
    <input type="password" class="form-control" name="password" [(ngModel)]="model.password" required>
  </div>

  <div class="form-group">
    <label>Hobbies</label>
    <select class="form-control" name="hobbies" [(ngModel)]="hobbies">
      <option value="">Select an option</option>
      <option *ngFor="let hoby of Hobbies" [value]="hoby">
        {{hoby}}
      </option>
    </select>
  </div>

  <div class="form-group">
    <button class="btn btn-danger btn-block">Submit</button>
  </div>
</form>

To initiate the template-driven form, add a reference to the NgForm. Declare a template variable with the form by adding the #userForm="ngForm".

To submit the form add onSubmit(userForm) event on the form tag. When a user clicks on the submit button, then the input value will be passed through the onSubmit() method.

We also need to add a name property to the Angular 9 form To register the form control in the form, and it is required to be added.

The ngModel directive formulates a FormControl instance in the Angular form and attaches it with the form control item.

From the hobbies option, a user can select one hoby, add a select field to the form and define the options as Hobbies using *ngFor directive. The ngFor directive will iterate over Hobbies array and create the option tag for every option described in the array.

Open the app.component.ts file and add the following code.

import { Component } from '@angular/core';

export class User {
  public name: string;
  public email: string;
  public password: string;
  public hobbies: string;
}

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

export class AppComponent {
  model = new User();

  Hobbies: string[] = [
    'Acrobatics',
    'Acting',
    'Animation',
    'Astronomy',
    'Baking'
  ];

  constructor() { }

  onSubmit(form) {
    console.log(form.value)
  }
}

Define a property class for the form model; it carries the form field’s value and set the model instance with User Class.

Adding Validation in Template-driven Form

Our Angular form is working correctly, but we have to add validation in our form and convey a strong message to the user if the form fields are invalid.

<form #userForm="ngForm" (ngSubmit)="userForm.form.valid && onSubmit(userForm)">
  <div class="form-group">
    <label>Name</label>
    <input type="text" name="name" class="form-control" [(ngModel)]="model.name" #name="ngModel"
      [ngClass]="{ 'is-invalid': userForm.submitted && name.invalid }" required>
    <div class="invalid-feedback" *ngIf="userForm.submitted && name.invalid">
      <p *ngIf="name.errors.required">Name is required</p>
    </div>
  </div>
</form>

We add the required validation in the name field, to access the form control inside the template. We created the name variable and assigned to “ngModel”.

To add the Bootstrap form validation, we implemented the validation to the class. Class validation applies only when the user submits the form and form is invalid.

To show the error message we used the Angular *ngIf directive and checking the input condition on submission and if the form is invalid.

Same way we applied the form validation in other input fields. Open the app.component.html file and add the following code.

<form #userForm="ngForm" (ngSubmit)="userForm.form.valid && onSubmit(userForm)">
  <div class="form-group">
    <label>Name</label>
    <input type="text" name="name" class="form-control" [(ngModel)]="model.name" #name="ngModel"
      [ngClass]="{ 'is-invalid': userForm.submitted && name.invalid }" required>
    <div class="invalid-feedback" *ngIf="userForm.submitted && name.invalid">
      <p *ngIf="name.errors.required">Name is required</p>
    </div>
  </div>

  <div class="form-group">
    <label>Email</label>
    <input type="email" class="form-control" name="email" [(ngModel)]="model.email" #email="ngModel"
      [ngClass]="{ 'is-invalid': userForm.submitted && email.invalid }" email required>
    <div *ngIf="userForm.submitted && email.invalid" class="invalid-feedback">
      <div *ngIf="email.errors.required">Email is required</div>
      <div *ngIf="email.errors.email">Must be a valid email address</div>
    </div>
  </div>

  <div class="form-group">
    <label>Password</label>
    <input type="password" class="form-control" name="password" [(ngModel)]="model.password" #password="ngModel"
      [ngClass]="{ 'is-invalid': userForm.submitted && password.invalid }" minlength="8" required>
    <div *ngIf="userForm.submitted && password.invalid" class="invalid-feedback">
      <div *ngIf="password.errors.required">Password is required</div>
      <div *ngIf="password.errors.minlength">Password should be at least 8 characters long</div>
    </div>
  </div>

  <div class="form-group">
    <label>Hobbies</label>
    <select class="form-control" name="hobbies" [(ngModel)]="hobbies">
      <option value="">Select an option</option>
      <option *ngFor="let hoby of Hobbies" [value]="hoby">
        {{hoby}}
      </option>
    </select>
  </div>

  <div class="form-group">
    <button class="btn btn-danger btn-block">Submit</button>
  </div>
</form>

Conclusion

Finally, we have completed the Angular 9 Forms tutorial, and In this tutorial, we learned how to create Angular form with the template-driven approach.

We learnt how to implement Bootstrap in Angular and create forms with Bootstrap.

We looked at how to work with the ngModel directive to handle the Angular form data.

We looked at how to add validation in template-driven forms as well as how to submit a form.

To get the full code of this tutorial visit this GitHub repository.

Thanks a lot for reading this tutorial.

How to integrate Bootstrap 4 with Angular 9?

How to integrate Bootstrap 4 with Angular 9?

In this Angular 9 tutorial, we've seen different ways of integrating Bootstrap 4 in Angular 9 Apps. We will see how to use Bootstrap to style apps built using Angular 9.

In this tutorial, we will see how to use Bootstrap to style apps built using Angular 9.

We'll see how to integrate Angular with Bootstrap, in various ways including using ng-bootstrap and ngx-bootstrap packages.

We'll be using Angular CLI 9 for generating a brand new project.

These are the steps of our tutorial:

  • Step 1 - Installing Angular CLI v9
  • Step 2 - Installing Bootstrap 4 in Your Angular 9 Project
  • Step 3 (Method 1) - Adding Bootstrap 4 to Angular 9 Using angular.json
  • Step 3 (Method 2) - Adding Bootstrap 4 to Angular 9 Using index.html
  • Step 3 (Method 3) - Adding Bootstrap 4 to Angular 9 Using styles.css
  • Alternative Step - Adding Bootstrap 4 Using ng-bootstrap and ngx-bootstrap
What is Bootstrap

Bootstrap is the most popular HTML and CSS framework for building responsive layouts with ease and without having a deep knowledge of CSS (Still custom CSS is required to customize your design ane make it different from the other Bootstrap-styled websites unless you are using a BS theme developed specifically for you).

Bootstrap 4 is the latest version of BS which brings many new and powerful features to the framework most importantly Flexbox which is now the default display system for BS grid layout (one of the most important features of BS).

3+ Ways to Include Bootstrap 4 In Your Angular Project

This can be done in multiple ways:

  • Including the Bootstrap CSS and JavaScript files in the <head> section of the index.html file of your Angular project with a <link> and <script> tags,

  • Importing the Bootstrap CSS file in the global styles.css file of your Angular project with an @import keyword.

  • Adding the Bootstrap CSS and JavaScript files in the styles and scripts arrays of the angular.json file of your project

Step 1 - Installing Angular CLI v9

Let's get started by installing Angular CLI v9 if it is not yet installed on your machine.

Head over to a new command-line interface and run the following command to install the latest version of the Angular CLI:

$ npm install -g @angular/[email protected]

At the time of writing this tutorial, Angular 9 is still in pre-release, so we need to use the next tag to install it. Angular v9.0.0-rc.2 is installed.

Note: This will install the Angular CLI globally on your system so depending on your npm configuration you may need to add sudo (for superuser access) in macOS and Linux or use a command prompt with admin access in Windows.

After the installation, you'll have at your disposal the ng utility. Let's use it to generate a new Angular 9 project.

$ ng new angular-bootstrap-examples

You will be prompted for a couple of questions:

? Would you like to add Angular routing? Yes
? Which stylesheet format would you like to use? (Use arrow keys)
> CSS
  SCSS   [ https://sass-lang.com/documentation/syntax#scss                ]
  Sass   [ https://sass-lang.com/documentation/syntax#the-indented-syntax ]
  Less   [ http://lesscss.org                                             ]
  Stylus [ http://stylus-lang.com                                         ]

Most importantly, choose CSS as the stylesheet format because we'll use ths CSS version of Bootstrap in our tutorial.

The command will generate the directory structure and necessary files for the project and will install the required dependencies.

Next, navigate inside the root folder of your project

$ cd angular-bootstrap-examples

You can then serve your Angular 9 application using the ng serve command as follows:

$ ng serve

Your app will be served from http://localhost:4200/

Step 2 - Installing Bootstrap 4 in Your Angular 9 Project

In this step, we'll proceed to add Bootstrap 4 to our Angular 9 application.

There are various ways that you can use to install Bootstrap in your project:

  • Installing Bootstrap from npm using the npm install command,
  • Downloading Bootstrap files and adding them to the src/assets folder of your Angular project,
  • Using Bootstrap from a CDN.

Let's proceed with the first method. Go back to your command-line interface and install Bootstrap 4 via npm as follows:

 $ npm install --save bootstrap

This will also add the bootstrap package to package.json.

As the time of writing this tutorial, bootstrap v4.3.1 will be installed.

The Bootstrap 4 assets will be installed in the node_modules/bootstrap folder. You'll need to tell Angular where to look for them.

Next, you also need to install jQuery using the following command:

 $ npm install --save jquery

At the time of this tutorial jquery v3.4.1 will be installed.

Step 3 (Method 1) - Adding Bootstrap 4 to Angular 9 Using angular.json

Open the angular.json file of your project and include:

  • node_modules/bootstrap/dist/css/bootstrap.css in the projects->architect->build->styles array,
  • node_modules/bootstrap/dist/js/bootstrap.js in the projects->architect->build->scripts array,
  • node_modules/bootstrap/dist/js/bootstrap.js in the projects->architect->build->scripts array,

As follows:

{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1, 
  "newProjectRoot": "projects",
  "projects": {
    "angular-bootstrap-examples": {
      "projectType": "application",
      "schematics": {},
      "root": "",
      "sourceRoot": "src",
      "prefix": "app",
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist/angular-bootstrap-examples",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "tsconfig.app.json",
            "aot": true,
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "./node_modules/bootstrap/dist/css/bootstrap.css",
              "src/styles.css"              
            ],
            "scripts": [
              "./node_modules/jquery/dist/jquery.js",
              "./node_modules/bootstrap/dist/js/bootstrap.js"
            ]
          },

Note: You also need to add the jQuery JavaScript library file.

Step 3 (Method 2) - Adding Bootstrap 4 to Angular 9 Using index.html

You can also include Bootstrap files from node_modules/bootstrap using the index.html file.

Open the src/index.html file and add the following:

  • A <link> tag for adding the bootstrap.css file in the <head> section,
  • A <script> tag for adding the jquery.js file before the closing </body> tag,
  • A <script> tag for adding the bootstrap.js file before the </body> tag.
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Angular Bootstrap 4 Examples</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <link rel="stylesheet" href="../node_modules/bootstrap/dist/css/bootstrap.css">

</head>
<body>
  <app-root></app-root>
  <script src="../node_modules/jquery/dist/jquery.js"></script>
  <script src="../node_modules/bootstrap/dist/js/bootstrap.js"></script>    
</body>
</html>

Step 3 (Method 3) - Adding Bootstrap 4 to Angular 9 Using styles.css

We can also use the styles.css file to add the CSS file of Bootstrap to our project.

Open the src/styles.css file of your Angular project and import the bootstrap.css file as follows:

@import "~bootstrap/dist/css/bootstrap.css"

This replaces the previous method(s) so you don't need to add the file to the styles array of the angular.json file or to the index.html file.

Note: The JS file(s) can be added using the scripts array or the <script> tag as the previous methods.

Alternative Step - Adding Bootstrap 4 Using ng-bootstrap and ngx-bootstrap

Bootstrap depends on jQuery and Popper.js libraries, and if you don't include them in your project, any Bootstrap components that rely on JavaScript will not work.

Why not include those libs? For Angular it's better to avoid using libraries that make direct manipulation of the DOM (like jQuery) and let Angular handle that.

Now what if you need the complete features of Bootstrap 4 without the JS libraries?

A better way is to use component libraries created for the sake of making Bootstrap work seamlessly with Angular such as ng-bootstrap or ngx-bootstrap

So first you'll need to install the library from npm using the following command:

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

Once you finish the installation you'll need to import the main module.

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

Next you'll need to add the module you imported in your app root module

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

@NgModule({
  declarations: [/*...*/],
  imports: [/*...*/, NgbModule.forRoot()],
  /*...*/
})
export class AppModule {
}

Please note that ng-bootstrap requires the Bootstrap 4 CSS file to be present.

You can add it in the styles array of the angular.json file like that:

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

Now you can use Bootstrap 4 in your Angular application.

You can find all the available components via this link.

You can also use the ngx-bootstrap library

Simply head back to your terminal, make sure you are inside your Angular project then run the following command to install ngx-bootstrap

npm install ngx-bootstrap --save

You also need the Bootstrap 4 CSS files. Add the following line in the <head> of your Angular app which includes Bootstrap from a CDN

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet">

You can also install bootstrap from npm and use the previous way to include the CSS file (via the styles array in the angular-cli.json file)

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

Next open src/app/app.module.ts and add

import { BsDropdownModule} from 'ngx-bootstrap/dropdown';
import { AlertModule } from 'ngx-bootstrap';

/*...*/

@NgModule({
   /*...*/
   imports: [BsDropdownModule.forRoot(),AlertModule.forRoot(), /*...*/ ],
    /*...*/ 
})

This an example of importing two components BsDropdownModule and AlertModule.

You need to import the module for each component you want to use in the same way.

ngx-bootstrap provides each BS component in each own module so you only import the components you need. In this way your app will be smaller since it bundles only the components you are actually using.

You can find all the available components that you can use from the docs

Adding Bootstrap 4 to Angular 9

Thanks to the new ng add command added on Angular 7+, you have a new simpler and easier way to add Bootstrap without using the npm install command for installing the required dependencies or adding any configurations.

You can simply run the following command to add ng-bootstrap:

$ ng add @ng-bootstrap/schematics

That's it. You now have support for Bootstrap components and styles without any extra configurations. You also don't need jQuery since we are using ng-bootstrap.

Conclusion

In this article, we've seen different ways of including Bootstrap 4 in Angular 9 apps:

  • Using original Bootstrap 4 assets from npm,
  • Using the ng-bootstrap library,
  • And finally using the ngx-bootstrap

The most important difference between ng-bootstrap vs. ngx-bootstrapis that ngx-bootstrap uses separate modules for components to reduce the final app size.

How to add Bootstrap 4 to your Angular 8 Project?

How to add Bootstrap 4 to your Angular 8 Project?

In this Angular 8 tutorial, I will give you example of how to add Bootstrap 4 in Angular 8 Project. As we know Bootstrap is the world’s most popular framework for building responsive, and mobile-first sites. Bootstrap provide several class for making responsive website for your mobile.

Here, I will give you example of how to add Bootstrap 4 in Angular 8 project. You can easily install Bootstrap in Aangular 8. I will also give you example of how to use bootstrap in Angular 8. You can easily understand Angular 8 install Bootstrap 4 and use it.

As we know Bootstrap is the world’s most popular framework for building responsive, and mobile-first sites. bootstrap provide several class for making responsive website for your mobile. So if you want to use bootstrap with angular 8 than I will help you very simple way.

I have a two install bootstrap and use it with your Angular 8 project. I will give you both way example bellow.

You can easily create your angular app using bellow command:

ng new my-new-app

Example 1:

In this solution, you need to just install bootstrap on your angular 8 and import css file to style.css file. this is only for css importing. so you can run command bellow:

npm install bootstrap --save

Ok, now you need to import your bootstrap css on style.css file as like bellow:

src/style.css

@import "~bootstrap/dist/css/bootstrap.css";

Now you can use bootstrap class in your angular 8 app. It will works.

Example 2:

In this solution, we will also install bootstrap with jquery and popper js. so that way you can also import bootstrap css and bootstrap js function. So i think this will be best solution for you i think.

let's run following commands:

npm install bootstrap --save
npm install jquery --save
npm install popper.js --save

Now after successfully run above command. let's import it in angular.json file.

angular.json

{

  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",

  "version": 1,

  "newProjectRoot": "projects",

  "projects": {

    "my-app": {

      "projectType": "application",

      "schematics": {},

      "root": "",

      "sourceRoot": "src",

      "prefix": "app",

      "architect": {

        "build": {

          "builder": "@angular-devkit/build-angular:browser",

          "options": {

            "outputPath": "dist/my-app",

            "index": "src/index.html",

            "main": "src/main.ts",

            "polyfills": "src/polyfills.ts",

            "tsConfig": "tsconfig.app.json",

            "aot": false,

            "assets": [

              "src/favicon.ico",

              "src/assets"

            ],

            "styles": [

              "node_modules/bootstrap/dist/css/bootstrap.min.css",

              "src/styles.css"

            ],

            "scripts": [

                "node_modules/jquery/dist/jquery.min.js",

                "node_modules/bootstrap/dist/js/bootstrap.min.js"

            ]

          },

          .....

Now you can use bootstrap css and js both.

Now you can check your angular 8 project.

I hope it can help you...