Edupala

Comprehensive Full Stack Development Tutorial: Learn Ionic, Angular, React, React Native, and Node.js with JavaScript

The best approach for installing and using Bootstrap in angular 14?

angular bootstrap

There are many different ways of installing Bootstrap in Angular. In Angular, we have different UI libraries like Angular material, others, and Bootstrap also. There are different ways of installing Bootstrap in Angular like CDN, Bootstrap Library build specifically for Angular. In this tutorial, we’ll learn different ways of installing Bootstrap and what is the best approach to using Bootstrap in Angular.

In this article, we have three goals behind this tutorial. First, we will learn correct way of installing bootstrap in the angular project. Secondly, we explore the difference between bootstrap and ng-bootstrap. At last, how to use the bootstrap component in our Angular project? Let’s get started.


Different ways of adding Bootstrap in Angular 13|14?

There are many 3rd party libraries to add the bootstrap framework to our Angular project. But we must know which and what is based on your Angular project. We will discuss different ways of adding bootstrap and discuss its advantages or disadvantages of it.

LibraryDescriptionFiles Size
@ng-bootstrap/ng-bootstrapMost downloaded as compared to other libraries. Is built specifically for Angular, not dependent on JQuery which is javascript as Angular use typescript. We can use bootstrap components that are built specifically for Angular and are ready to use.3.87 MB
ngx-bootstrapIt provides Bootstrap components powered by Angular, so you don’t need to include original JS components.13.7 MB
bootstrapIs general for all web development, but it also includes javascript files, which we don’t need in Angular. So better use 1st and 2nd which are built for Angular.8.63 MB
Bootstrap CDNUsing Bootstrap CDN, in Angular index.html.8.63 MB
Options for installing Bootstrap in Angular

Using Bootstrap CDN in Angular project is not used, we only get CSS style only, but @ng-bootstrap and ngx-bootstrap are the best options, both of these libraries are built specifically for Angular. Both of these libraries have lots of build components like tables, cards, modal, carousal, and more, these components are ready to use and we don’t need to create components from scratch.


Best approach of adding bootstrap in Angular

Angular also have its own UI library called Angular material design from Google, it’s the individual choice of using UI libraries based on your requirement. If you want to use bootstrap then the best way is to use the first two.

  1. ng-bootstrap: Built specifically for Angular.
  2. ngx-bootstrap: Built specifically for Angular.

The ng-bootstrap and ngx-bootstrap libraries have no dependencies on 3rd party JavaScript. Bootstrap uses plain JavaScript and JQuery. Angular uses Typescript, so it would not be recommended to use Bootstrap directly in Angular and it may cause an issue while dealing with JavaScript of Bootstrap and JQuery. But we can still use the CSS part of it, an ng-bootstrap library that is compatible with Angular and doesn’t need JQuery.

Then is recommended to use the first two approaches to add the bootstrap components in Angular instead of installing the whole bootstrap. This makes us easy to use Bootstrap components in your Angular application. Both ngx-bootstrap and ng-bootstrap have a lot of ready-made bootstrap components and these two libraries are built specifically for Angular.

Both bootstrap and ng-bootstrap are front-end frameworks created by Twitter. Angular ng-bootstrap is built specifically for Angular. The official definition of ng-bootstrap is “Angular widgets built from the ground up using only Bootstrap 4 CSS with APIs designed for the Angular ecosystem”.

If you have not yet installed an Angular CLI on your system. Then we need to install an Angular first. Angular CLI allows us to create an Angular project, generate application and library code, and perform a variety of ongoing development tasks such as testing, bundling, and deployment. To install the Angular CLI, open a terminal and run the following command:

npm install -g @angular/cli

Method 1: Using ng-bootstrap Library

The ng-bootstrap library allows us to use the bootstrap components in angular, this library has components and directives built specifically for Angular. Bootstrap is a popular open-source CSS framework for building responsive, mobile-first web apps.

How to install Bootstrap in angular using ng-bootstrap Library?

Before angular 9, installing Bootstrap in angular, we manually need to add NgbModule from angular ng-bootstrap in the app.module.ts file but this is not the case in angular 9 and above. We just run the command below only to install and configure bootstrap in angular. The steps of installing Bootstrap using ng-bootstrap.

  1. Create an Angular project to used the Bootstrap component in Angular.
  2. Install or add ng-bootstrap in the Angular project.
  3. The used Bootstrap component in Angular project.

Let’s first create an Angular project and install ng-bootstrap.

ng new bootstrapApp
cd bootstrapApp
ng add @ng-bootstrap/ng-bootstrap

The ng-bootstrap has good documentation, is easy to use and the file size is also very small. The third command will create an Angular bootstrap project for us. The above command will install bootstrap and add NgbModule automatically in our app.module.ts file. We can use our ng-bootstrap component directly in our angular project without any further configuration like importing bootstrap CSS in our project.

Angular bootstrap example using ng-bootstrap

The ng-bootstrap allows us to use the bootstrap component in our angular project. The ng-bootstrap has a large number of premade components that are ready to use in our angular project. Let’s first use the table component from bootstrap. Here is a screenshot of our first Angular bootstrap example.

bootstrap in angular
Angular bootstrap example

We can use any of the ng-bootstrap components it provides to us. Let’s add some ng-bootstrap components. We will use a basic table and rating components. Edit the app.component.html template and typescript file

<p>Table is just a mapping of objects to table rows with <code>ngFor</code></p>

<table class="table table-striped">
  <thead>
  <tr>
    <th scope="col">#</th>
    <th scope="col">Country</th>
    <th scope="col">Area</th>
    <th scope="col">Population</th>
  </tr>
  </thead>
  <tbody>
  <tr *ngFor="let country of countries; index as i">
    <th scope="row">{{ i + 1 }}</th>
    <td>
      <img [src]="'https://upload.wikimedia.org/wikipedia/commons/' + country.flag" class="mr-2" style="width: 20px">
      {{ country.name }}
    </td>
    <td>{{ country.area | number }}</td>
    <td>{{ country.population | number }}</td>
  </tr>
  </tbody>
</table>

Here we have to define iterate through countries array object to display country data and image containing country flag. We haven’t added any CSS style for the table, all table styles, stripe line, and responsive are taken from bootstrap only.

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

interface Country {
  name: string;
  flag: string;
  area: number;
  population: number;
}

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  countries: Country[] = [
    {
      name: 'Russia',
      flag: 'f/f3/Flag_of_Russia.svg',
      area: 17075200,
      population: 146989754
    },
    {
      name: 'Canada',
      flag: 'c/cf/Flag_of_Canada.svg',
      area: 9976140,
      population: 36624199
    },
    {
      name: 'United States',
      flag: 'a/a4/Flag_of_the_United_States.svg',
      area: 9629091,
      population: 324459463
    },
  ];
}

If you want to learn how to add pagination on the table and filter using bootstrap, we had an article on it.

Angular bootstrap example 2 using its modal component

Let’s continue from the previous example, here we’ll demonstrate an example of Angular bootstrap modal to display country information in detail. Here is a screenshot of our Angular bootstrap modal.

Angular bootstrap modal
Angular bootstrap example

Let’s create a country model for our country’s data, create folder models, add a file called the country.ts file and add the following code.

export interface Country {
    name: string;
    flag: string;
    area: number;
    population: number;
}

Let’s create a detail component which is our Angular bootstrap modal, where we are getting data from the app component and display in it. Run the command below to generate the Angular bootstrap modal component called detail.

ng generate component components/detail

Edit our Angular bootstrap modal component

In our detail component modal, we are displaying details of each country. Let edit the components/detail.component.ts file.

import { Component, Input } from '@angular/core';
import { Country } from '../../../models/Country';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';

@Component({
  selector: 'app-detail',
  templateUrl: './detail.component.html',
  styleUrls: ['./detail.component.scss']
})
export class DetailComponent {
  @Input() country?: Country;

  constructor(public activeModal: NgbActiveModal) { }

}

Here we need to import NgbActiveModal from ng-bootstrap, we need this to perform modal operations like the closing of the modal. We have to use the @Input decorator to get country data from the app.component.html file and let edit the detail.component.html template to display our country data.

<div class="modal-header">
    <h4 class="modal-title">Information: {{ country?.name }}</h4>
    <button type="button" class="close" aria-label="Close" (click)="activeModal.dismiss('Cross click')">
        <span aria-hidden="true">&times;</span>
    </button>
</div>
<div class="modal-body">
    <div class="card country-border">
        <img class="card-img-top" 
        [src]="'https://upload.wikimedia.org/wikipedia/commons/' + country?.flag"
            alt="Card image cap">
        <div class="card-body">
            <p class="card-text"><b>Name : </b>{{ country?.name }}</p>
            <p class="card-text"><b>Area : </b>{{ country?.area }}</p>
            <p class="card-title"><b>Population : </b>{{ country?.population }}</p>
        </div>
    </div>
</div>
<div class="modal-footer">
    <button type="button" class="btn btn-outline-dark" (click)="activeModal.close('Close click')">Close</button>
</div>

In our detail modal, we have two buttons that allow us to dismiss or close the modal component.

Edit App component to pass data to Angular bootstrap modal

We need to edit our app.component.ts file to pass country data to our angular bootstrap modal detail component and we need to import our DetailComponent modal.

import { Component } from '@angular/core';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { DetailComponent } from './components/detail/detail.component';
import { Country } from './models/country';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  currentRate = 8;
  countries: Country[] = [
    {
      name: 'Russia',
      flag: 'f/f3/Flag_of_Russia.svg',
      area: 17075200,
      population: 146989754
    },
    {
      name: 'India',
      flag: "4/41/Flag_of_India.svg",
      area: 3287263,
      population: 1324171354
    },
    {
      name: 'Canada',
      flag: 'c/cf/Flag_of_Canada.svg',
      area: 9976140,
      population: 36624199
    },
    {
      name: 'United States',
      flag: 'a/a4/Flag_of_the_United_States.svg',
      area: 9629091,
      population: 324459463
    },
  ];

  constructor(private modalService: NgbModal) { }

  open(country: Country) {
    const modalRef = this.modalService.open(DetailComponent);
    modalRef.componentInstance.country = country;
  }
}

Edit app.component.html, as we need to add an edit button for each country in the countries list to pass data from the app component to our bootstrap modal.

<p>Table is just a mapping of objects to table rows with <code>ngFor</code></p>
<table class="table table-striped">
  <thead>
    <tr>
      <th scope="col">#</th>
      <th scope="col">Country</th>
      <th scope="col">Area</th>
      <th scope="col">Population</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let country of countries; index as i">
      <th scope="row">{{ i + 1 }}</th>
      <td>
        <img [src]="'https://upload.wikimedia.org/wikipedia/commons/' + country.flag" class="mr-2" style="width: 20px">
        {{ country.name }}
      </td>
      <td>{{ country.area | number }}</td>
      <td>{{ country.population | number }}</td>
      <button type="button" c class="btn btn-info" (click)="open(country)">Country Details</button>
    </tr>
  </tbody>
</table>
<router-outlet></router-outlet>

Angular bootstrap example 3

Last we’ll demonstrate how to use the angular bootstrap carousel, as ng-bootstrap has a carousel component to implement it in our Angular, Here is a screenshot of our example of the angular bootstrap carousel.

angular bootstrap carousel example
Angular bootstrap Carousel example

Let’s edit our component to add a carousel to our project.

<ngb-carousel *ngIf="images" class="text-lg-center">
  <ng-template ngbSlide>
    <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>
    <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>
    <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>

Add image array object in component typescript file as below.

  images = [944, 1011, 984].map((n) => `https://picsum.photos/id/${n}/900/500`);

Note: We need to add class=”text-lg-center” to the carousel component so we can make the ng-bootstrap carousel center.


Method 2: Using ng-bootstrap Library for Bootstrap in Angular

We can use the ng-bootstrap library, which is also a popular library for adding bootstrap components in Angular. This library has lots of built-in Bootstrap components ready to use. The steps of installing Bootstrap using ng-bootstrap.

  1. Create an Angular project to use the Bootstrap component in Angular.
  2. Install or add ngx-bootstrap in the Angular project.
  3. Add individual component modules inside the app.module.ts file.
  4. Add Bootstrap CSS 4 CDN in index.html in the Angular project.
  5. The used Bootstrap component in the Angular project.

Let’s first create an Angular project and install ng-bootstrap.

ng new bootstrapApp
cd bootstrapApp
ng add ngx-bootstrap

Once we had installed ngx-bootstrap in Angular, we need to add Bootstrap CSS CDN in index.html, lets’s do it.

<!doctype html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <title>BootstrapApp</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="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css"
    integrity="sha384-zCbKRCUGaJDkqS1kPbPd7TveP5iyJE0EjAuZQTgFLD2ylzuqKfdKlfG/eSrtxUkn" crossorigin="anonymous">
</head>

<body>
  <app-root></app-root>
</body>

</html>

Example of ngx-bootstrap component

Let’s demonstrate the progress component from the ngx-bootstrap example. Here is a screenshot of our example.

ngx-bootstrap example

First, we need to add progressbar modules in the app.module.ts file

...
import { ProgressbarModule } from 'ngx-bootstrap/progressbar';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    ....
    ProgressbarModule.forRoot()
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Let’s add the progressbar component in the app.component.html file.

<div class="container mt-4">
  <div class="mb-2">
    <progressbar [max]="max" [value]="dynamic">
      <span class="text-nowrap">{{ dynamic }} / {{ max }}</span>
    </progressbar>
    <small><em>No animation</em></small>
  </div>
  <div class="mb-2">
    <progressbar [animate]="false" [value]="dynamic" type="success">
      <b>{{ dynamic }}%</b>
    </progressbar>
    <small><em>Object (changes type based on value)</em></small>
  </div>

  <div class="mb-3">
    <progressbar
      class="progress-striped active"
      [value]="dynamic"
      [type]="type"
    >
      {{ type }}
    </progressbar>
  </div>
  <button type="button" class="btn btn-sm btn-primary" (click)="random()">
    Randomize
  </button>
</div>

Now let’s define the variable which we have used in the progress bar component in the app.component.ts file.

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  max = 200;
  showWarning?: boolean;
  dynamic = 0;
  type: 'success' | 'info' | 'warning' | 'danger' = 'info';
 
  constructor() { this.random(); }
 
  random(): void {
    const value = Math.floor(Math.random() * 100 + 1);
    let type: 'success' | 'info' | 'warning' | 'danger';
    if (value < 25) {
      type = 'success';
    } else if (value < 50) {
      type = 'info';
    } else if (value < 75) {
      type = 'warning';
    } else {
      type = 'danger';
    }
 
    this.dynamic = value;
    this.type = type;
  }
}

Conclusion
Bootstrap is free and open-source,  we can easily add Bootstrap components in Angular by using either ng-bootstrap or ngx-bootstrap. The ng-bootstrap in Angular widget is built only from Bootstrap 4 CSS with APIs designed for the Angular ecosystem. No dependencies on 3rd party JavaScript. I had added GitHub on the Angular bootstrap table with pagination and the search filter in Latest Angular 14 if you want to check here is the Github link. Please if you like it then please share it with others and on social networking, this will encourage me to add more details content.

Related Articles

The best approach for installing and using Bootstrap in angular 14?

One thought on “The best approach for installing and using Bootstrap in angular 14?

Leave a Reply

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

Scroll to top