如何在Angular项目中使用Bootstrap?

174

我正在启动我的第一个Angular应用程序,基本设置已完成。

如何将Bootstrap添加到我的应用程序中?

如果您能提供一个示例,那将是非常有帮助的。

20个回答

121

如果您使用Angular-CLI生成新项目,那么在Angular 2/4中使bootstrap可访问的另一种方法是:

  1. 通过命令行界面导航到项目文件夹。然后使用npm安装bootstrap:
    $ npm install --save bootstrap--save选项将使bootstrap出现在依赖项中。
  2. 编辑配置项目的.angular-cli.json文件。它在项目目录内。将一个引用添加到"styles"数组中。引用必须是与使用npm下载的bootstrap文件的相对路径。在我的情况下是:"../node_modules/bootstrap/dist/css/bootstrap.min.css"

我的示例.angular-cli.json文件:

{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "project": {
    "name": "bootstrap-test"
  },
  "apps": [
    {
      "root": "src",
      "outDir": "dist",
      "assets": [
        "assets",
        "favicon.ico"
      ],
      "index": "index.html",
      "main": "main.ts",
      "polyfills": "polyfills.ts",
      "test": "test.ts",
      "tsconfig": "tsconfig.app.json",
      "testTsconfig": "tsconfig.spec.json",
      "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"
      }
    }
  ],
  "e2e": {
    "protractor": {
      "config": "./protractor.conf.js"
    }
  },
  "lint": [
    {
      "project": "src/tsconfig.app.json"
    },
    {
      "project": "src/tsconfig.spec.json"
    },
    {
      "project": "e2e/tsconfig.e2e.json"
    }
  ],
  "test": {
    "karma": {
      "config": "./karma.conf.js"
    }
  },
  "defaults": {
    "styleExt": "css",
    "component": {}
  }
}

现在Bootstrap应该成为您默认设置的一部分。


1
我认为在这个解决方案中,应该将bootstrap.min.js也添加到“scripts”中。你同意吗? - hamalaiv
1
@hamalaiv 这至少不是强制性的。 - LaPriWa
3
按照 https://dev59.com/YJjga4cB1Zd3GeqPM59o#40054193 中的描述,我使用了步骤1安装了Bootstrap,并在我的src/styles.css文件中插入@import "../node_modules/bootstrap/dist/css/bootstrap.min.css"; 。对我来说,这篇文章中的步骤2并不必要,我正在使用@angular/cli:1.3.1。 - user3777549

77

通过 ng2-bootstrap 项目,也可以与 Angular2 集成:https://github.com/valor-software/ng2-bootstrap

要安装它,只需将这些文件放在您的主 HTML 页面中即可:

<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">
然后您可以这样在组件中使用它:
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 {
}

1
如果使用ng2-bootstrap版本,难道不应该使用捆绑的CSS吗?我不确定为什么要使用CDN CSS,或者这就是应该做的吗?我也是新手。 - Stephen York
6
新的Angular2中,@component内部不再包含指令。 - Master Yoda

38

你所需做的就是在你的index.html文件中引入Bootstrap CSS。

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

1
有没有办法从本地资源中包含它,而不是使用CDN? - SparK
1
是的,href 应该设置为本地文件的路径。如果您遇到问题,我建议从您正在使用的任何 Web 服务器中搜索“提供静态文件”。 - user2263572
它不适用于Angular 6+,对于除了index.html之外的文件。例如:app.component.html。请告知。 - GD- Ganesh Deshmukh

21

16

如果你打算使用Bootstrap 4,而这个版本是与angular-ui 团队的ng-bootstrap配合使用的,那么你需要使用以下代码(注意:你不需要包括JS文件):

  <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">

如果您正在使用SASS,可以在运行 npm install bootstrap@4.0.0-alpha.6 --save 后,在 styles.scss 文件中指向该文件进行本地引用:

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

1
请问您能否解释一下为什么不需要包含JS文件呢?是因为NPM已经安装了吗?此外,在Thierry Templier的示例中,他导入ng2-bootstrap/ng2-bootstrap以使用警报。在Bootstrap 4中使用方式是否相同? - BBaysinger
谢谢。我尝试了你的第二个例子。但是出现了一个错误,无法从node_modules加载资源。 - BBaysinger
1
请看更新的答案。如果你正在使用SASS,那么你可以像我一样在SASS文件中使用"@import"来导入它。如果没有,请尝试将其添加到您的“vendor.ts”文件中,但我在我的代码中没有使用它。 - occasl

10

最流行的选择是使用第三方库,例如作为npm包分发的ng2-bootstrap项目 https://github.com/valor-software/ng2-bootstrap 或者 Angular UI Bootstrap库。

我个人使用ng2-bootstrap。有许多配置方式,因为配置取决于你的Angular项目的构建方式。下面我将基于Angular 2 QuickStart项目https://github.com/angular/quickstart展示一个示例配置。

首先我们在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"
  },
... }

那么我们需要在 systemjs.config.js 中将名称映射到正确的URL。

(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);

我们需要在index.html中导入bootstrap.css文件。我们可以从硬盘上的/node_modules/bootstrap目录中获取它(因为我们添加了bootstrap 3.3.7依赖项),或者从web上获取。在此,我们是从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>

我们应该从 /app 目录下编辑我们的 app.module.ts 文件。

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 { }

最后是我们的应用程序/app目录下的app.component.ts文件

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

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

export class AppComponent {

    constructor() { }

}

在运行应用程序之前,我们需要安装Bootstrap和ng2-bootstrap依赖项。我们应该进入项目目录并键入以下命令:

npm install

最终我们可以开始我们的应用程序

npm start

在ng2-bootstrap项目的GitHub上有许多代码示例,展示了如何将ng2-bootstrap导入到各种Angular 2项目中。甚至还有plnkr样本。Valor-software(该库的作者)网站上还有API文档。


9
在angular-cli环境中,我发现最简单的方法如下:
1. 在使用s̲c̲s̲s̲样式表的环境中解决方案:
npm install bootstrap-sass —save

在style.scss中:
$icon-font-path: '~bootstrap-sass/assets/fonts/bootstrap/';
@import '~bootstrap-sass/assets/stylesheets/bootstrap';

注1:字符“~”是指“nodes_modules”文件夹。
注2:由于我们使用scss,我们可以自定义所有想要的bootstrap变量。


2. 在具有c̲s̲s̲样式表的环境中的解决方案

npm install bootstrap —save

在 style.css 中:

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

6

有几种方法可以将Angular2与Bootstrap配置起来,其中最完整的方法之一是使用ng-bootstrap。通过这种配置,我们使algular2能够完全控制DOM,避免了使用JQuery和Boostrap.js的需要。

1-以使用Angular-CLI创建的新项目为起点,并使用命令行安装ng-bootstrap:

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

注意:更多信息请访问https://ng-bootstrap.github.io/#/getting-started 2-然后我们需要安装Bootstrap来使用CSS和网格系统。
npm install bootstrap@4.0.0-beta.2 --save

注意:更多信息请参见https://getbootstrap.com/docs/4.0/getting-started/download/ 现在我们已经设置好了环境,需要修改.angular-cli.json文件,在样式中添加以下内容:
"../node_modules/bootstrap/dist/css/bootstrap.min.css"

这里有一个例子:

"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"
      }
    }
  ]

下一步是将ng-bootstrap模块添加到我们的项目中,为此需要在app.module.ts中添加:
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';

然后将新模块添加到应用程序中:NgbModule.forRoot()

示例:

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

现在我们可以在我们的Angular2/5项目中开始使用Bootstrap4。

3
只需检查您的package.json文件并添加bootstrap依赖项。
"dependencies": {

   "bootstrap": "^3.3.7",
}

然后在.angular-cli.json文件中添加以下代码

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

最后,您只需使用终端更新本地的npm即可。
$ npm update

3
我有同样的问题,并找到了这篇文章,其中提供了一个非常干净的解决方案: http://leon.radley.se/2017/01/angular-cli-and-bootstrap-4/ 以下是说明,但使用了我简化的解决方案:
安装Bootstrap 4(说明):
npm install --save bootstrap@4.0.0-alpha.6

如果需要,将您的 src/styles.css 重命名为 styles.scss 并更新 .angular-cli.json 反映这种变化:
"styles": [
  "styles.scss"
],

然后将这行代码添加到 styles.scss 文件中:
@import '~bootstrap/scss/bootstrap';

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接