Angular2使用boostrap和ng-bootstrap总结

Angular2使用bootstrap有几种方式,本文主要介绍两种方式进行Boostrap样式的使用:

一、直接通过静态文件的方式进行引入:

通过命令新建一个Bootstrap的工程

ng new Bootstrap
npm install

接着在src下的assets下新建一个bootstrap文件夹,将相关的boostrap文件进行引入。

在src目录下的styles.css文件里头进行样式的引入:

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

测试下功能,在app.component.html添加一下代码:

<!-- Standard button -->
<button type="button" class="btn btn-default">(默认样式)Default</button>

<!-- Provides extra visual weight and identifies the primary action in a set of buttons -->
<button type="button" class="btn btn-primary">(首选项)Primary</button>

<!-- Indicates a successful or positive action -->
<button type="button" class="btn btn-success">(成功)Success</button>

<!-- Contextual button for informational alert messages -->
<button type="button" class="btn btn-info">(一般信息)Info</button>

<!-- Indicates caution should be taken with this action -->
<button type="button" class="btn btn-warning">(警告)Warning</button>

<!-- Indicates a dangerous or potentially negative action -->
<button type="button" class="btn btn-danger">(危险)Danger</button>

<!-- Deemphasize a button by making it look like a link while maintaining button behavior -->
<button type="button" class="btn btn-link">(链接)Link</button>

敲打ng serve 浏览器敲打http://localhost:4200

可以看到bootstrap样式效果生效了。

 第二种:用angular ng-boostrap进行样式的安装使用

2.1新建工程

ng new my-app --style=scss  带style参数原因:ng-bootstrap要求使用scss

安装相关依赖npm install

2.2 安装相关ng-boostrap依赖

npm install @ng-bootstrap/ng-bootstrap bootstrap@next --save  安装ng-bootstrap和bootstrap

2.3添加bootstrap.min.css引用
工程根目录下,打开.angular-cli.json文件,在styles中添加bootstrap.min.css引用

  "styles": [
    "../node_modules/bootstrap/dist/css/bootstrap.min.css",  此行为新添加
     "styles.scss"
   ]

2.4 在src目录下的styles.scss文件中添加如下内容

  @import '../node_modules/bootstrap/scss/bootstrap';

2.5在src的app目录下, 找得到app.module.ts类中引用NgbModule

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

 在imports里头新增 NgbModule.forRoot()

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

2.6添加模板

在src的app目录下的app.component.html中开头添加如下内容

 <p>
  <ngb-alert type="success" [dismissible]="false">
    <strong>Success!</strong> Good work.
  </ngb-alert>

  </p>

2.7启动验证 ng serve

浏览器输入:http://localhost:4200

 

如果npm失败了,找个网络好的地方,多试几次,

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

在末尾加上-f/-force表示重新安装,多试几次一般是可以的。

原文地址:https://www.cnblogs.com/shawWey/p/7881994.html