ANGULAR
Complete Angular Tutorial For Beginners Introduction to Angular | What is Angular? Architecture Overview & Concepts of Angular How to Install Angular How to Create a new project in Angular Bootstrapping in Angular: How It Works Internally Angular Components Overview & Examples Data Binding in Angular Interpolation in Angular Property Binding in Angular Event Binding in Angular ngModel & Two way Data binding in Angular NgModelChange & Change Event in Angular Child/Nested Components in Angular angular directives angular ngFor directive ngSwitch, ngSwitchcase, ngSwitchDefa ult Angular Example How to use ngIf, else, then in Angular By example NgClass Example Conditionally apply class Angular ngStyle Directive Angular Trackby to improve ngFor Performance How to Create & Use Custom Directive In Angular Working with Angular Pipes How to Create Custom Pipe in Angular Formatting Dates with Angular Date Pipe Using Angular Async Pipe with ngIf & ngFor angular keyValue pipe Using Angular Pipes in Components or Services Angular Component Communication & Sharing Data Angular Pass data to child component Angular Pass data from Child to parent component Component Life Cycle Hooks in Angular Angular ngOnInit And ngOnDestroy Life Cycle hook Angular ngOnChanges life Cycle Hook Angular ngDoCheck Life Cycle Hook Angular Forms Tutorial: Fundamentals & Concep t s Angular Template-driven forms example How to set value in template-driven forms in Angular Angular Reactive Forms Example Using Angular FormBuilder to build Forms SetValue & PatchValue in Angular StatusChanges in Angular Forms ValueChanges in Angular Forms FormControl in Angular FormGroup in Angular Angular FormArray Example Nested FormArray Example Add Form Fields Dynamically SetValue & PatchValue in FormArray Angular Select Options Example in Angular Introduction to Angular Services Introduction to Angular Dependency Injection Angular Injector, @Injectable & @Inject Angular Providers: useClass, useValue, useFactory & useExisting Injection Token in Angular How Dependency Injection & Resolution Works in Angular Angular Singleton Service ProvidedIn root, any & platform in Angular @Self, @SkipSelf & @Optional Decorators Angular '@Host Decorator in Angular ViewProviders in Angular Angular Reactive Forms Validation Custom Validator in Angular Reactive Form Custom Validator with Parameters in Angular Inject Service Into Validator in Angular template_driven_form_validation_in_angular Custom Validator in Template Driven Forms in Angular Angular Async Validator Example Cross Field or Multi Field Validation Angular How to add Validators Dynamically using SetValidators in Angular Angular HttpClient Tutorial & Example Angular HTTP GET Example using httpclient Angular HTTP POST Example URL Parameters, Query Parameters, httpparams in Angular HttpClient Angular HTTPHeaders Example Understanding HTTP Interceptors in Angular Angular Routing Tutorial with Example Location Strategy in Angular Angular Route Params Angular : Child Routes / Nested Route Query Parameters in Angular Angular Pass Data to Route: Dynamic/Static RouterLink, Navigate & NavigateByUrl to Navigate Routes RouterLinkActive in Angular Angular Router Events ActivatedRoute in Angular Angular Guards Tutorial Angular CanActivate Guard Example Angular CanActivateChild Example Angular CanDeactivate Guard Angular Resolve Guard Introduction to Angular Modules or ngModule Angular Routing between modules Angular Folder Structure Best Practices Guide to Lazy loading in Angular Angular Preloading Strategy Angular CanLoad Guard Example Ng-Content & Content Projection in Angular Angular @input, @output & EventEmitter Template Reference Variable in Angular ng-container in Angular How to use ng-template & TemplateRef in Angular How to Use ngTemplateOutlet in Angular '@Hostbinding and @Hostlistener_in_Angular Understanding ViewChild, ViewChildren &erylist in Angular ElementRef in Angular Renderer2 Example: Manipulating DOM in Angular ContentChild and ContentChildren in Angular AfterViewInit, AfterViewChecked, AfterContentInit & AfterContentChecked in Angular Angular Decorators Observable in Angular using RxJs Create observable from a string, array & object in angular Create Observable from Event using FromEvent in Angular Using Angular observable pipe with example Angular Map Operator: Usage and Examples Filter Operator in Angular Observable Tap operator in Angular observable Using SwitchMap in Angular Using MergeMap in Angular Using concatMap in Angular Using ExhaustMap in Angular Take, TakeUntil, TakeWhile & TakeLast in Angular Observable First, Last & Single Operator in Angular Observable Skip, SkipUntil, SkipWhile & SkipLast Operators in Angular The Scan & Reduce operators in Angular DebounceTime & Debounce in Angular Delay & DelayWhen in Angular Using ThrowError in Angular Observable Using Catcherror Operator in Angular Observable ReTryWhen inReTry, ReTryWhen in Angular Observable Unsubscribing from an Observable in Angular Subjects in Angular ReplaySubject, BehaviorSubject & AsyncSubject in Angular Angular Observable Subject Example Sharing Data Between Components Angular Global CSS styles View Encapsulation in Angular Style binding in Angular Class Binding in Angular Angular Component Styles How to Install & Use Angular FontAwesome How to Add Bootstrap to Angular Angular Location Service: go/back/forward Angular How to use APP_INITIALIZER Angular Runtime Configuration Angular Environment Variables Error Handling in Angular Applications Angular HTTP Error Handling Angular CLI tutorial ng new in Angular CLI How to update Angular to latest version Migrate to Standalone Components in Angular Create Multiple Angular Apps in One Project Set Page Title Using Title Service Angular Example Dynamic Page Title based on Route in Angular Meta service in Angular. Add/Update Meta Tags Example Dynamic Meta Tags in Angular Angular Canonical URL Lazy Load Images in Angular Server Side Rendering Using Angular Universal The requested URL was not found on this server error in Angular Angular Examples & Sample Projects Best Resources to Learn Angular Best Angular Books in 2020

How to Add Bootstrap to Angular

In this guide, we will show you how to add Bootstrap to the Angular app. This tutorial uses Bootstrap 4 & Angular 9. We will show you how to install the bootstrap CSS. We also show you how to add ng-bootstrap & ngx-bootstrap two most popular Angular implementation of the Bootstrap using the Angular CLI commands.

What is Bootstrap

The bootstrap is a responsive mobile-first CSS framework for building Web Applications. It is open source and has all the features like Sass variables, mixins, responsive grid system, prebuilt components, and powerful JavaScript plugins.

Bootstrap consists of few CSS files & JS files.

The CSS files contains all the styles definitions.

Many of bootstrap components require the use of JavaScript to function. For Example, carousels, drop-down menus, auto-suggest, etc require bootstraps.js file. It also has depedency on jQuery, Popper.js.

Create a new Angular Application

Create a new Angular Application bootstrap-example, as shown below. Use the Angular CLI Command ng new.

                              
ng new Bootstrap-example
                            
                        

Open the app.component.html and add the following code. The example bootstrap code is from the Hoverable rows

                              

<h1> Angular Bootstrap Example</h1>
 
<table class="table table-hover">
  <thead>
    <tr>
      <th scope="col">#</th>
      <th scope="col">First</th>
      <th scope="col">Last</th>
      <th scope="col">Handle</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th scope="row">1</th>
      <td>Mark</td>
      <td>Otto</td>
      <td>@mdo</td>
    </tr>
    <tr>
      <th scope="row">2</th>
      <td>Jacob</td>
      <td>Thornton</td>
      <td>@fat</td>
    </tr>
    <tr>
      <th scope="row">3</th>
      <td colspan="2">Larry the Bird</td>
      <td>@twitter</td>
    </tr>
  </tbody>
</table>
 
                            
                        

Run the app. Note that we have not yet added the bootstrap CSS. This will render the HTML table without any styles as shown below.

Adding Bootstrap CSS File

If you are not using any of the components that use JavaScript, then you do not need to install JS files. There are a few ways in which you can add the CSS Files.

We can install the Bootstrap CSS file in one of the following ways

  1. Use the CSS file from a CDN
  2. Copy the bootstrap.min.css file to a local folder
  3. Install the bootstrap npm package

Once installed, you can include it in the app by using the one of the methods

  1. Add it in Index.html using the link tag
  2. Include it in angular.json
  3. Import it in styles.css

Add Bootstrap using the CDN

Open the index.html and add the following code. The link to the latest version of bootstrap CSS

                              

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
 
                            
                        

The index.html is as shown below.

                              

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>BootstrapCSSExample</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://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" 
      integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" 
      crossorigin="anonymous">
</head>
<body>
  <app-root></app-root>
</body>
</html>
 
 
                            
                        

Now run the app, and you should be able to see tables rendered as shown in the Hoverable rows example.

Alternatively, you can use the @import directive in the styles.css file

                              
@import "https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
 
                            
                        

Install the bootstrap package

Instead of running from CDN, you can install the CSS Files locally. The correct way to do this is by installing the bootstrap package.

Run the following npm command to install bootstrap. This will install the latest version of the bootstrap which is bootstrap 4.3.1 right now.

                              
npm install --save bootstrap
                            
                        

Running the above command will copy the bootstrap files to the node_modules/bootstrap folder. But it will not include it in the app.

Open the angular.json file and locate the projects -> Bootstrap-example (our project name) -> architect -> build -> styles node.

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

Alternatively you can just add the @import directive to import it in the styles.css

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

Copy CSS file Local folder

You can manually copy the CSS files to any of local folder.

Assets folder

Copy the bootstrap.min.css to the src/assets folder. The Angular CLI includes all the files from the assets folder to the distribution folder (i.e dist/assets folder).

Hence, you can add it in the index.html as shown below. Note that the path must be with reference to the index.html.

                              

<link rel="stylesheet" href="assets/bootstrap.min.css">
                            
                        

or Include it under styles node in angular.json.

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

Or import it in styles.css.

                              

@import "~assets/bootstrap.min.css";  
                            
                        

Other folders

You can also copy it to any other folder other than the assets folder.

For example copy bootstrap.min.css to the root folder i.e src folder.

You can add it in the styles node in angular.json

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

or import it in the styles.css

                              

@import "~assets/bootstrap.min.css";
                            
                        

Adding Bootstrap CSS & JS File

The above methods add only the bootstrap CSS Files. But bootstrap also comes with bootstrap.js file, which also depends on jQuery, Popper.js. You can also include them in the index.html, but it is not the Angular way as they manipulate the DOM directly and can interfere with the working of the Angular

There are two Angular specific bootstrap libraries available, which does the work in Angular way. One is ng-bootstrap & the other one is ngx-bootstrap

Installing ng-bootstrap

ng-bootstrap supports only Bootstrap 4 CSS and does not have dependencies on 3rd party JavaScript.

You can use npm command to install ng-bootstrap but the recommended way is to use the Angular CLI . i.e. using the ng command instead of npm command.

Using Angular CLI to install ng-bootstrap

                              
 
ng add @ng-bootstrap/ng-bootstrap
 
                            
                        

The above command

  1. Installs ng-bootstrap.
  2. Installs bootstrap.
  3. Updates the package.json
  4. Updates angular.json to use the bootstrap.min.css
  5. Imports the NgbModule in app.module.ts and add it in the imports array
  6. Updates the src/polyfills.ts

Here are the list of changes

package.json
                              
 
  "@ng-bootstrap/ng-bootstrap": "^6.2.0",
  "bootstrap": "^4.4.0",
 
                            
                        
angular.json
                              

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

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';        //NgbModule  Added here
 
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    NgbModule                                   //NgbModule                        
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
 
                            
                        
src/polyfills.ts
                              

/***************************************************************************************************
 * Load `$localize` onto the global scope - used if i18n tags appear in Angular templates.
 */
import '@angular/localize/init';
 
                            
                        

Using npm to install ng-bootstrap

If you use npm then you need to install both ng-bootstrap/ng-bootstrap & also bootstrap as shown below

                              

npm i @ng-bootstrap/ng-bootstrap --save
npm i bootstrap --save
 
                            
                        

And then makes changes to the package.json, angular.json, app.module.ts & src/polyfills.ts as shown in the previous section.

Using ng-bootstrap

The ng-bootstrap comes with a lot of components. You can refer to the list of ng-bootstrap components

The following is the code from ngbDropdown component from the drop down example. Add it into the app.component.html

                              

<div class="row">
  <div class="col">
    <div ngbDropdown class="d-inline-block">
      <button class="btn btn-outline-primary" id="dropdownBasic1" ngbDropdownToggle>Toggle dropdown</button>
      <div ngbDropdownMenu aria-labelledby="dropdownBasic1">
        <button ngbDropdownItem>Action - 1</button>
        <button ngbDropdownItem>Another Action</button>
        <button ngbDropdownItem>Something else is here</button>
      </div>
    </div>
  </div>
 
  <div class="col text-right">
    <div ngbDropdown placement="top-right" class="d-inline-block">
      <button class="btn btn-outline-primary" id="dropdownBasic2" ngbDropdownToggle>Toggle dropup</button>
      <div ngbDropdownMenu aria-labelledby="dropdownBasic2">
        <button ngbDropdownItem>Action - 1</button>
        <button ngbDropdownItem>Another Action</button>
        <button ngbDropdownItem>Something else is here</button>
      </div>
    </div>
  </div>
</div>
 
                            
                        

Reference

Installing ngx-bootstrap

ngx-bootstrap allows us to use both bootstrap 3 & 4. We can use the ether ng or npm command to install the ngx-bootstrap as shown below.

Using Angular CLI to install ngx-bootstrap

                              

ng add ngx-bootstrap
                            
                        

The command installs the ngx-bootstrap & bootstrap 4. It also updates the package.json, angular.json & app.module.ts. The following are a list of changes in each file.

package.json
                              

    "bootstrap": "4.1.1",
    "ngx-bootstrap": "^5.6.1",
                            
                        
angular.json
                              
 
"styles": [
    "./node_modules/bootstrap/dist/css/bootstrap.min.css",
    "./node_modules/ngx-bootstrap/datepicker/bs-datepicker.css",
    "src/styles.css"
],
 
                            
                        

app.module.ts. Note that BrowserAnimationsModule module is added & imported as it uses it extensively. Also note that no ngx-bootstrap related modules are added.

                              
 
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
 
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';   //added by ngx-bootstrap
 
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    BrowserAnimationsModule     //added by ngx-bootstrap
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
                            
                        

Using npm to install ngx-bootstrap

                              

npm install ngx-bootstrap bootstrap --save
                            
                        

The above command installs the ngx-bootstrap with bootstrap 4. You also need to make changes to the file angular.json & app.module.ts as shown in the previous section.

Using ngx-bootstrap

The ngx-bootstrap comes with a lot of components. You can refer to the list of ngx-bootstrap components.

The following code shows how to use the dropdowns component.

Each component in ngx-bootstrap comes with its own module. We need to import it in our root module to use it. Open the app.module.ts and import the BsDropdownModule from the ngx-bootstrap/dropdown. And also include it in the imports array using the BsDropdownModule.forRoot()

                              
 
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
 
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { BsDropdownModule } from 'ngx-bootstrap/dropdown';
 
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    BrowserAnimationsModule,
    BsDropdownModule.forRoot()
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
 
 
                            
                        

Now, open the app.component.html

                              
 
<h1>Angular ngx-bootstrap example</h1>
 
<div class="btn-group" dropdown>
  <button id="button-basic" dropdownToggle type="button" class="btn btn-primary dropdown-toggle"
          aria-controls="dropdown-basic">
    Button dropdown <span class="caret"></span>
  </button>
  <ul id="dropdown-basic" *dropdownMenu class="dropdown-menu"
      role="menu" aria-labelledby="button-basic">
    <li role="menuitem"><a class="dropdown-item" href="#">Action</a></li>
    <li role="menuitem"><a class="dropdown-item" href="#">Another action</a></li>
    <li role="menuitem"><a class="dropdown-item" href="#">Something else here</a></li>
    <li class="divider dropdown-divider"></li>
    <li role="menuitem"><a class="dropdown-item" href="#">Separated link</a>
    </li>
  </ul>
</div>
 
                            
                        

Run the app and you should see the button dropdown as shown in this document

Reference

  1. Home
  2. GitHub
  3. npm
  4. Documentation

Summary

We look at various ways to add the bootstrap in Angular. We also learned how to add bootstrap via ng-bootstrap & ngx-bootstrap libraries.