本文转自:https://loiane.com/2017/08/how-to-add-bootstrap-to-an-angular-cli-project/

In this article we will learn how to setup an Angular project with Bootstrap 3 or Bootstrap 4.

Update May 2018: code updated to Angular v6. Stackblitz link also available at the end of this article.

Contents

Although the setup seems simple, I still get a lot of questions on how to setup an Angular project generated with Angular CLI with Bootstrap. So let’s see the step by step in the sections below.

1: Creating an Angular project with Angular CLI

The first step is creating your Angular project using Angular CLI.

For this example we will use the following command:

ng new angular-bootstrap-example

2: Installing Bootstrap from NPM

Next, we need to install Bootstrap. Change the directory to the project we created (cd angular-bootstrap-example) and execute the following command:

For Bootstrap 3:

npm install bootstrap@3.3.7

For Bootstrap 4:

npm install bootstrap

2.1: Alternative: Local Bootstrap CSS

As an alternative, you can also download the Bootstrap CSS and add it locally to your project. I donwloaded Bootstrap from the website and created a folder styles (same level as styles.css):

Don’t place your local CSS files under assets folder. When we do the production build with Angular CLI, the CSS files declared in the angular.json will be minified and all styles will be bundled into a single styles.css. The assets folder is copied to the dist folder during the build process (the CSS code will be duplicated). Only place your local CSS files under assets in case you are importing them directly in the index.html.

3: Importing the CSS

We have two options to import the CSS from Bootstrap that was installed from NPM:

1: Configure angular.json:

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

2: Import directly in src/style.css or src/style.scss:

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

I personally prefer to import all my styles in src/style.css since it’s been declared in angular.json already.

3.1 Alternative: Local Bootstrap CSS

If you added the Bootstrap CSS file locally, just import it in angular.json

"styles": [
"styles/bootstrap-3.3.7-dist/css/bootstrap.min.css",
"styles.scss"
],

or src/style.css:

@import './styles/bootstrap-3.3.7-dist/css/bootstrap.min.css';

With this setup we are able to start using the Bootstrap CSS classes in our project.

4: Bootstrap JavaScript Components with ngx-bootstrap (Option 1)

In case you don’t need to use Bootstrap JavaScript components (that require JQuery), this is all the setup you need. But if you need to use modals, accordion, datepicker, tooltips or any other component, how can we use these components without installing jQuery?

There is an Angular wrapper library for Bootstrap called ngx-bootstrap that we can also install from NPM:

npm install ngx-bootstrap --save

ng2-bootstrap and ngx-bootstrap are the same package. ng2-bootstrap was renamed to ngx-bootstrap after #itsJustAngular.

In case you want to install Bootstrap and ngx-bootstrap at the same time when you create your Angular CLI project:

npm install bootstrap ngx-bootstrap --save

4.1: Adding the required Bootstrap modules in app.module.ts

Go through the ngx-bootstrap and add the modules needed in your app.module.ts. For example, suppose we want to use the Dropdown, Tooltip and Modal components:

import { BsDropdownModule } from 'ngx-bootstrap/dropdown';
import { TooltipModule } from 'ngx-bootstrap/tooltip';
import { ModalModule } from 'ngx-bootstrap/modal'; @NgModule({
imports: [
BrowserModule,
BsDropdownModule.forRoot(),
TooltipModule.forRoot(),
ModalModule.forRoot()
],
// ...
})
export class AppBootstrapModule {}

Because we call the .forRoot() method for each module (due the ngx-bootstrap module providers), the functionalities will be available in all components and modules of your project (global scope).

As an alternative, if you would like to organize the ngx-bootstrap in a different module (just for organization purposes in case you need to import many bs modules and don’t want to clutter your app.module), you can create a module app-bootstrap.module.ts, import the Bootstrap modules (using forRoot()) and also declare them in the exports section (so they become available to other modules as well).

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common'; import { BsDropdownModule } from 'ngx-bootstrap/dropdown';
import { TooltipModule } from 'ngx-bootstrap/tooltip';
import { ModalModule } from 'ngx-bootstrap/modal'; @NgModule({
imports: [
CommonModule,
BsDropdownModule.forRoot(),
TooltipModule.forRoot(),
ModalModule.forRoot()
],
exports: [BsDropdownModule, TooltipModule, ModalModule]
})
export class AppBootstrapModule {}

At last, don’t forget to import your bootstrap module in you app.module.ts.

import { AppBootstrapModule } from './app-bootstrap/app-bootstrap.module';

@NgModule({
imports: [BrowserModule, AppBootstrapModule],
// ...
})
export class AppModule {}

ngx-bootstrap works with Bootstrap 3 and 4. And I also made some tests and most of the functionalities also work with Bootstrap 2.x (yes, I still have some legacy code to maintain).

5: Let’s code!

Now that we have the setup for CSS and JavaScript components completed, let’s add some code to our app.component.html:

<nav class="navbar navbar-default">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand">
<img src="assets/img/ngx-bootstrap.svg" class="logo">
</a>
<span class="navbar-brand">Angular + Bootstrap</span>
</div>
<ul class="nav navbar-nav">
<li class="active"><a href="#">
Link <span class="sr-only">(current)</span>
</a></li>
<li><a href="#">Link</a></li>
<li class="dropdown" dropdown> <!-- {1} -->
<a dropdownToggle role="button"> <!-- {2} -->
Dropdown <span class="caret"></span></a>
<ul *dropdownMenu class="dropdown-menu"> <!-- {3} -->
<li><a href="#">Action</a></li>
<li><a href="#">Another action</a></li>
<li><a href="#">Something else here</a></li>
<li role="separator" class="divider"></li>
<li><a href="#">Separated link</a></li>
<li role="separator" class="divider"></li>
<li><a href="#">One more separated link</a></li>
</ul>
</li>
</ul>
</div>
</nav>

For the DropDown component, ngx-bootstrap provides some directives:

{1}dropdown directive: use this directive instead of class="dropdown".

{2}dropdownToggle directive: use this directive instead of class="dropdown-toggle" data-toggle="dropdown". It will also add the aria atributes to the HTML element.

{3}dropdownMenu directive: use this directive instead of class="dropdown-menu".

And you’ll have the same behavior as Bootstrap + Jquery:

Let’s also develop a button with a tooltip:

<button type="button" class="btn btn-primary"
tooltip="Vivamus sagittis lacus vel augue laoreet rutrum faucibus.">
Button with tooltip
</button>

The tooptip directive has the same effect as data-toggle="tooltip" title="Tooltip text".

Let’s also take a look how to use a Modal component:

<button type="button" class="btn btn-info"
(click)="openModal(template)">Create template modal</button> <ng-template #template>
<div class="modal-header">
<h4 class="modal-title pull-left">Modal</h4>
<button type="button" class="close pull-right"
aria-label="Close" (click)="modalRef.hide()">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="modal-body">
This is a modal.
</div>
</ng-template>

In the code above, note the we are using a ng-template as container of our modal template. This template is being referenced by a template local variable template. When the user clicks on the button, we tell our code to open the modal referenced by template (you can have as many modals as needed, just give different names to your local variables).

There is also a close button in the modal that is calling modalRef.hide().

So we need some TypeScript code in our app.component.ts as well:

import { BsModalRef, BsModalService } from 'ngx-bootstrap/modal';

@Component({
// ..
})
export class AppComponent {
public modalRef: BsModalRef; // {1}
constructor(private modalService: BsModalService) {} // {2} public openModal(template: TemplateRef<any>) {
this.modalRef = this.modalService.show(template); // {3}
}
}

{1}: first we need a variable to keep a reference of our modal. This is going to be used to close the modal.

{2}: to show the modal, we also need the ngx-bootstrap service

{3}: and when the user clicks on the button to open the popup we keep the modal reference and pass the template local name to the modalService.

ngx-bootstrap source code is still using Angular v2.x. Since there were no major breaking changes from v2.x to v.4x, it’s ok to use with v4.x. However, some ngx-bootstrap components use <template> instead of <ng-template>, so you might get warnings in your browser console related to template being deprecated. For the examples, such as the modal, replace templatewith ng-template in your code and you should be fine.

We have an Angular project using Bootstrap and did not need to import JQuery to have the same behavior!

6: Bootstrap 4 JavaScript Components with ng-bootstrap (Option 2)

There is also a second option to use Bootstrap JavaScript components in Angular without JQuery in case you are using Bootstrap 4: ng-bootstrap.

You can install ng-bootstrap in your project from NPM:

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

In your app.module.ts you need to import the NgbModule.forRoot() using the forRoot() method.

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

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

If you have feature modules in your application, you also need to import NgbModule, but without the forRoot() method:

Other modules in your application can simply import NgbModule:

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

@NgModule({
// ...
imports: [NgbModule, ...],
})
export class OtherModule {
}

Source code + live demo + Stackblitz

Source code available on GitHub

Live demo

Stackblitz online demo

References:

Happy coding!

[转]How to Add Bootstrap to an Angular CLI project的更多相关文章

  1. Using Sass with the Angular CLI

    https://www.tuicool.com/articles/mauiMzY One of the first things you'll usually do in a project is t ...

  2. Configure a proxy for your API calls with Angular CLI

    Table of contents Local development setup with Angular Issue: Dev server plus backend API Configurin ...

  3. 从Java角度理解Angular之入门篇:npm, yarn, Angular CLI

    本系列从Java程序员的角度,带大家理解前端Angular框架. 本文重点介绍Angular的开发.编译工具:npm, yarn, Angular CLI,它们就像Java在中的Maven,同时顺便介 ...

  4. (转载)从Java角度理解Angular之入门篇:npm, yarn, Angular CLI

    本系列从Java程序员的角度,带大家理解前端Angular框架. 本文是入门篇.笔者认为亲自动手写代码做实验,是最有效最扎实的学习途径,而搭建开发环境是学习一门新技术最需要先学会的技能,是入门的前提. ...

  5. @angular/cli项目构建--组件

    环境:nodeJS,git,angular/cli npm install -g cnpm --registry=https://registry.npm.taobao.org cnpm instal ...

  6. Angular环境准备和Angular cli

    Angular4.0来了,更小,更快,改动少 接下来为Angular4.0准备环境和学会使用Angular cli项目 1.环境准备: 1)在开始工作之前我们必须设置好开发环境 如果你的机器上还没有安 ...

  7. Angular CLI 安装和使用

    1.背景介绍 关于Angular版本,Angular官方已经统一命名Angular 1.x同一为Angular JS:Angular 2.x及以上统称Angular: CLI是Command Line ...

  8. .Net Core + Angular Cli / Angular4 开发环境搭建

    一.基础环境配置 1.安装VS 2017 v15.3或以上版本 2.安装VS Code最新版本 3.安装Node.js v6.9以上版本 4.重置全局npm源,修正为 淘宝的 NPM 镜像: npm  ...

  9. [Docker] Running Multiple Containers for an Angular, Node project

    The code is from Plusight course, github link is here. In this post, we will give a overview about h ...

随机推荐

  1. stm32f10x_it.c、stm32f10x_it.h和stm32f10x_conf.h文件作用

    如上图,在STM32的Keil工程文件(Project)中一般都包含stm32f10x_it.c.stm32f10x_it.h和stm32f10x_conf.h这三个文件,但是在ST官方提供的标准库“ ...

  2. centos7下zabbix记录

    Zabbixrpm -ivh http://repo.zabbix.com/zabbix/3.2/rhel/7/x86_64/zabbix-release-3.2-1.el7.noarch.rpm - ...

  3. hive -help hive命令行执行sql参数

    在shell命令行执行 hive -help 结果如下: -d,--define <key=value> Variable substitution to apply to Hive co ...

  4. 自定义Token的CAS登录

    工作中实际遇到的需求,我们有一个旧系统,用了CAS的单点登录,现在有一个外部系统,准备从它那里单点进来,这个外部系统提供了一个token参数来标记这是哪一个用户,我们用他们提供的方式解析出对应的用户, ...

  5. 初探系列 — Pharbers用于单点登录的权限架构

    一. 前言 就职公司 法伯科技是一家以数据科技为驱动, 专注于医药健康领域的循证咨询公司. 以数据科学家身份, 赋能医药行业. 让每位客户都能享受数据带来的价值, 洞察业务, 不止于数据, 让决策更精 ...

  6. FFmpeg Android 学习(一):Android 如何调用 FFMPEG 编辑音视频

    一.概述 在Android开发中,我们对一些音视频的处理比较无力,特别是编辑音视频这部分.而且在Android上对视频编辑方面,几乎没有任何API做支持,MediaCodec(硬编码)也没有做支持.那 ...

  7. Metasploit Framework(7)客户端渗透(下)

    文章的格式也许不是很好看,也没有什么合理的顺序 完全是想到什么写一些什么,但各个方面都涵盖到了 能耐下心看的朋友欢迎一起学习,大牛和杠精们请绕道 应用场景: Kali机器IP:192.168.163. ...

  8. [Postman]定制Postman(4)

    自定义请求方法 您可以在Postman中自定义请求方法以满足特定要求.创建自己的请求方法后,您将能够发送/保存它们. 此功能允许您保存/删除自定义方法,还可以删除默认方法.单击请求方法下拉区域,键入方 ...

  9. kafka扫盲笔记,实战入门

    Kafka作为大数据时代的产物,自有其生存之道.让我们跟随扫盲班的培训,进行大致了解与使用kafka吧.(平时工作有使用不代表就知道kafka了哟) 1. kafka介绍 1.1. 拥有的能力(能干什 ...

  10. SpringBoot集成Thymeleaf模板引擎

    简单介绍 目前在JavaEE领域有几中比较常用的模板引擎,分别是Jsp.Velocity.Freemarker.Thymeleaf,对Freemark语法不是特别熟悉,不过对于前端页面渲染效率来说,j ...