[angular] How to use Bootstrap in an Angular project?

I am starting my first Angular application and my basic setup is done.

How can I add Bootstrap to my application?

If you can provide an example then it would be a great help.

The answer is


  1. npm install --save bootstrap
  2. go to -> angular-cli.json file, find styles properties and just add next sting: "../node_modules/bootstrap/dist/css/bootstrap.min.css", It might be looks like this:

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

There are several ways to configure angular2 with Bootstrap, one of the most complete ways to get the most of it is to use ng-bootstrap, using this configuration we give to algular2 complete control over our DOM, avoiding the need to use JQuery and Boostrap.js.

1-Take as a starting point a new project created with Angular-CLI and using the command line, install ng-bootstrap:

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

Note: More info at https://ng-bootstrap.github.io/#/getting-started

2-Then we need to install bootstrap for the css and the grid system.

npm install [email protected] --save

Note: More info at https://getbootstrap.com/docs/4.0/getting-started/download/

Now we have the setup the environment and for that we have to change the .angular-cli.json adding to the style:

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

Here is an example:

"apps": [
    {
      "root": "src",
        ...
      ],
      "index": "index.html",
       ...
      "prefix": "app",
      "styles": [
        "../node_modules/bootstrap/dist/css/bootstrap.min.css",
        "styles.css"
      ],
      "scripts": [],
      "environmentSource": "environments/environment.ts",
      "environments": {
        "dev": "environments/environment.ts",
        "prod": "environments/environment.prod.ts"
      }
    }
  ]

The next step is to add the ng-boostrap module to our project, to do so we need to add on the app.module.ts:

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

Then add the new module to the application app: NgbModule.forRoot()

Example:

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

Now we can start using bootstrap4 on our angular2/5 project.


Procedure with Angular 6+ & Bootstrap 4+ :

  1. Open a shell on the folder of your project
  2. Install bootstrap with the command : npm install --save [email protected]
  3. Bootstrap need the dependency jquery, so if you don't have it, you can install it with the command : npm install --save jquery 1.9.1
  4. You may need to fix vulnerability with the command : npm audit fix
  5. In your main style.scss file, add the following line : @import "../node_modules/bootstrap/dist/css/bootstrap.min.css";

OR

Add this line to your main index.html file : <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">


If you use angular cli, after adding bootstrap into package.json and install the package, all you need is add boostrap.min.css into .angular-cli.json's "styles" section.

One important thing is "When you make changes to .angular-cli.json you will need to re-start ng serve to pick up configuration changes."

Ref:

https://github.com/angular/angular-cli/wiki/stories-include-bootstrap


I was looking for same answer and finally I found this link. You can find explained three different ways how to add bootstrap css into your angular 2 project. It helped me.

Here is the link: http://codingthesmartway.com/using-bootstrap-with-angular/


My recommendation would be instead of declaring it in the json stylus to put it in the scss so that everything is compiled and in one place.

1)install bootstrap with npm

 npm install bootstrap

2) Declare bootstrap npm in the css with our styles

Create _bootstrap-custom.scss:

  // Required
  @import "bootstrap-custom-required";


  // Optional
  @import "~bootstrap/scss/root";
  @import "~bootstrap/scss/grid";
  @import "~bootstrap/scss/tables";

    ...
    ..
    .

3) Within the styles.scss we insert

@import "bootstrap-custom";

so we will have all our core compiled and in one place


Another very good (better?) alternative is to use a set of widgets created by the angular-ui team: https://ng-bootstrap.github.io


In an angular-cli environment, the most straightforward way I've found is the following:


1. Solution in an environment with s_c_s_s_ stylesheets

npm install bootstrap-sass —save

In style.scss:

$icon-font-path: '~bootstrap-sass/assets/fonts/bootstrap/';
@import '~bootstrap-sass/assets/stylesheets/bootstrap';

Note1: The ~ character is a reference to nodes_modules folder.
Note2: As we are using scss, we can customize all boostrap variables we want.


2. Solution in an environment with c_s_s_ stylesheets

npm install bootstrap —save

In style.css:

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

The most popular option is to use some third party library distributed as npm package like ng2-bootstrap project https://github.com/valor-software/ng2-bootstrap or Angular UI Bootstrap library.

I personally use ng2-bootstrap. There are many ways to configure it, because configuration depends on how your Angular project is build. Underneath I post example configuration based on Angular 2 QuickStart project https://github.com/angular/quickstart

Firstly we add dependencies in our package.json

    { ...
"dependencies": {
    "@angular/common": "~2.4.0",
    "@angular/compiler": "~2.4.0",
    "@angular/core": "~2.4.0",

    ...

    "bootstrap": "^3.3.7",
    "ng2-bootstrap": "1.1.16-11"
  },
... }

Then we have to map names to proper URL's in systemjs.config.js

(function (global) {
  System.config({
    ...
    // map tells the System loader where to look for things
    map: {
      // our app is within the app folder
      app: 'app',

      // angular bundles
      '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
      '@angular/common': 'npm:@angular/common/bundles/common.umd.js',
      '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
      '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
      '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
      '@angular/http': 'npm:@angular/http/bundles/http.umd.js',
      '@angular/router': 'npm:@angular/router/bundles/router.umd.js',
      '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',

      //bootstrap
      'moment': 'npm:moment/bundles/moment.umd.js',
      'ng2-bootstrap': 'npm:ng2-bootstrap/bundles/ng2-bootstrap.umd.js',

      // other libraries
      'rxjs':                      'npm:rxjs',
      'angular-in-memory-web-api': 'npm:angular-in-memory-web-api/bundles/in-memory-web-api.umd.js'
    },
...
  });
})(this);

We have to import bootstrap .css file in index.html. We can get it from /node_modules/bootstrap directory on our hard drive (because we added bootstrap 3.3.7 dependency) or from web. There we are obtaining it from web:

<!DOCTYPE html>
<html>
  <head>
    ...
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    ...
  </head>

  <body>
    <my-app>Loading...</my-app>
  </body>
</html>

We should edit our app.module.ts file from /app directory

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

//bootstrap alert import part 1
import {AlertModule} from 'ng2-bootstrap';

import { AppComponent }  from './app.component';


@NgModule({
  //bootstrap alert import part 2
  imports:      [ BrowserModule, AlertModule.forRoot() ],
  declarations: [ AppComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

And finally our app.component.ts file from /app directory

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

@Component({
    selector: 'my-app',
    template: `
    <alert type="success">
        Well done!
    </alert>
    `
})

export class AppComponent {

    constructor() { }

}

Then we have to install our bootstrap and ng2-bootstrap dependencies before we run our app. We should go to our project directory and type

npm install

Finally we can start our app

npm start

There are many code samples on ng2-bootstrap project github showing how to import ng2-bootstrap to various Angular 2 project builds. There is even plnkr sample. There is also API documentation on Valor-software (authors of the library) website.


An integration with Angular2 is also available through the ng2-bootstrap project : https://github.com/valor-software/ng2-bootstrap.

To install it simply put these files in your main HTML page:

<script src="https://cdnjs.cloudflare.com/ajax/libs/ng2-bootstrap/x.x.x/ng2-bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">

Then you can use it into your components this way:

import {Component} from 'angular2/core';
import {Alert} from 'ng2-bootstrap/ng2-bootstrap';

@Component({
  selector: 'my-app',
  directives: [Alert],
  template: `<alert type="info">ng2-bootstrap hello world!</alert>`
})
export class AppComponent {
}

Another very good alternative is to use the skeleton Angular 2/4 + Bootstrap 4

1) Download ZIP and extract zip folder

2) ng serve


All you need to do is include the boostrap css within your index.html file.

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">

Add this to your package.json , “dependency”

"bootstrap": "^3.3.7",

In .angular-cli.json file, to your “Styles” add

"../node_modules/bootstrap/dist/css/bootstrap.css"

update your npm by using this command

npm update


add the following lines in your html page

<script src="https://cdnjs.cloudflare.com/ajax/libs/ng2-bootstrap/x.x.x/ng2-bootstrap.min.js"></script>

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

You can try to use Prettyfox UI library http://ng.prettyfox.org

This library use bootstrap 4 styles and not need jquery.


just check your package.json file and add dependencies for bootstrap

"dependencies": {

   "bootstrap": "^3.3.7",
}

then add below code on .angular-cli.json file

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

Finally you just update your npm locally by using terminal

$ npm update

I had the same question and found this article with a really clean solution:

http://leon.radley.se/2017/01/angular-cli-and-bootstrap-4/

Here are the instructions, but with my simplified solution:

Install Bootstrap 4 (instructions):

npm install --save [email protected]

If needed, rename your src/styles.css to styles.scss and update .angular-cli.json to reflect the change:

"styles": [
  "styles.scss"
],

Then add this line to styles.scss:

@import '~bootstrap/scss/bootstrap';

If you plan on using Bootstrap 4 which is required with the angular-ui team's ng-bootstrap that is mentioned in this thread, you'll want to use this instead (NOTE: you don't need to include the JS file):

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

You can also reference this locally after running npm install [email protected] --save by pointing to the file in your styles.scss file, assuming you're using SASS:

@import '../../node_modules/bootstrap/dist/css/bootstrap.min.css';

Examples related to angular

error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class error TS1086: An accessor cannot be declared in an ambient context in Angular 9 TS1086: An accessor cannot be declared in ambient context @angular/material/index.d.ts' is not a module Why powershell does not run Angular commands? error: This is probably not a problem with npm. There is likely additional logging output above Angular @ViewChild() error: Expected 2 arguments, but got 1 Schema validation failed with the following errors: Data path ".builders['app-shell']" should have required property 'class' Access blocked by CORS policy: Response to preflight request doesn't pass access control check origin 'http://localhost:4200' has been blocked by CORS policy in Angular7

Examples related to twitter-bootstrap

Bootstrap 4: responsive sidebar menu to top navbar CSS class for pointer cursor How to install popper.js with Bootstrap 4? Change arrow colors in Bootstraps carousel Search input with an icon Bootstrap 4 bootstrap 4 responsive utilities visible / hidden xs sm lg not working bootstrap.min.js:6 Uncaught Error: Bootstrap dropdown require Popper.js Bootstrap 4 - Inline List? Bootstrap 4, how to make a col have a height of 100%? Bootstrap 4: Multilevel Dropdown Inside Navigation

Examples related to typescript

TS1086: An accessor cannot be declared in ambient context Element implicitly has an 'any' type because expression of type 'string' can't be used to index Angular @ViewChild() error: Expected 2 arguments, but got 1 Typescript: No index signature with a parameter of type 'string' was found on type '{ "A": string; } Understanding esModuleInterop in tsconfig file How can I solve the error 'TS2532: Object is possibly 'undefined'? Typescript: Type 'string | undefined' is not assignable to type 'string' Typescript: Type X is missing the following properties from type Y length, pop, push, concat, and 26 more. [2740] Can't perform a React state update on an unmounted component TypeScript and React - children type?

Examples related to twitter-bootstrap-3

bootstrap 4 responsive utilities visible / hidden xs sm lg not working How to change the bootstrap primary color? What is the '.well' equivalent class in Bootstrap 4 How to use Bootstrap in an Angular project? Bootstrap get div to align in the center Jquery to open Bootstrap v3 modal of remote url How to increase Bootstrap Modal Width? Bootstrap datetimepicker is not a function How can I increase the size of a bootstrap button? Bootstrap : TypeError: $(...).modal is not a function