JavaScript
Imal Perera  

How to use ng2-bootstrap with Angular-cli

Spread the love

Angular-Cli is the recommended way to create an angular 2 project, although it is still at the early stages many developers tend to use it. there is an awesome project going on right now called angular material2 which intended to provides rich material Components for angular developers but still this project is in Alph, we can expect lot of code rewriting before it comes to beta so it is still not good to go with production app.

Today we will look into another awesome library called ng2-bootstrap which aimed to rewrite all the jquery bootstrap components in Angular2. Angular 2 is lot more strict  with jquery than angular 1.x so it is always better to go with native Angular 2 components in your project.

It is little annoying if you are doing this for the first time, because of less documentation, so lets see how you do it correctly with angular-cli

Create Angular Project

click here to view how to setup angular cli

ng new ng2-bootstrap-example
cd ng2-bootstrap-example

How to install ng2-bootstrap 

npm install ng2-bootstrap --save
typings install moment --save

Configure project to work with ng2-bootstrap

edit angular-cli-build.js file like below

vendorNpmFiles: [
    'ng2-bootstrap/**/*',
     'moment/moment.js'
]

edit src/system-config.ts file like below

const map: any = {
  'moment': 'vendor/moment/moment.js',
  'ng2-bootstrap': 'vendor/ng2-bootstrap'
};
/** User packages configuration. */
const packages: any = {
  'ng2-bootstrap': {
    format: 'cjs',
    defaultExtension: 'js',
    main: 'ng2-bootstrap.js'
  },
  'moment':{
    format: 'cjs'
  }
};

Now we are almost done.

ng build

Above step will create files in the dist/vendor folder

Now all the steps related to js are done, we have one last thing to do, which is we need to link the bootstrap.css file. ng2-bootstrap does not comes with bootstrap css file so based on our preference we can add either bootstrap 3 or bootstrap 4, you can do this in two ways, you can either install bootstrap using npm or you can link the cdn file directly to the main html file

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

So we are now done, if you see any errors on the console terminate the existing server and restart it, make sure you do ng build as well.

 

You can checkout my github repo for more code 🙂

Leave A Comment