将 Bootstrap 4 添加到 Angular 6 或 Angular 7 应用程序

16

我正在使用 Bootstrap 4 开发 Angular 应用程序。

我需要有关在我的 Angular 应用程序中添加 scss 的帮助。

我的问题是:

  • 在 Angular 6 和 Angular 7 中添加 Bootstrap 4 scss 的方式是否相同?

即:

npm install bootstrap --save  

打开 angular.json 文件并将 Bootstrap 文件路径添加到样式部分。例如:

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

以上的方法对于 Angular 的两个版本是相同的吗?


是的。但请注意,在您的脚本部分中,jQuery 应该先于 Bootstrap JS。 - Hameed Syed
yes way is same as before - Pardeep Jain
我使用相同的方式。但是您还需要在脚本中包括theater和jQuery。 - André Pacheco
1
https://ng-bootstrap.github.io/#/home - Liam
请按照此博客文章 https://medium.com/@oyewusioyekunle/how-to-add-bootstrap-to-your-angular-project-angular-8-6379fd6a0f46 添加Bootstrap到您的Angular项目中。 - Zohab Ali
5个回答

29
你需要做以下事情: 将 Bootstrap 添加到 package.json(使用 npm install bootstrap --save 完成) 将 Bootstrap 添加到 angular.json(还需要 jQuery)
  "styles": [
     "styles.css".
     "../node_modules/bootstrap/dist/css/bootstrap.min.css"
  ],
  "scripts": [
     "../node_modules/jquery/dist/jquery.min.js",
     "../node_modules/popper.js/dist/umd/popper.min.js",
     "../node_modules/bootstrap/dist/js/bootstrap.min.js"
  ],

在 Angular 应用中引用 Bootstrap(app.module.ts)

import bootstrap from "bootstrap";

演示:https://codesandbox.io/s/kmm2q7zvko
文章:https://medium.com/wdstack/angular-7-bootstrap-4-starter-25573dff23f6


3
请使用 "styles.css", 而非 "styles.css". - Nizam Kazi
1
导入语句出错,'node_modules/@types/bootstrap"' 没有导出成员 'bootstrap'。 - The Doctor
在你的 app.module.ts 文件中,尝试像这样导入 bootstrapimport * as bootstrap from 'bootstrap'; - ChumiestBucket

9

选项1

执行

npm install bootstrap@4 jquery --save

Bootstrap 的 JavaScript 部分依赖于 jQuery,因此您需要 jQuery JavaScript 库文件。
"styles": [
    "src/styles.css","node_modules/bootstrap/dist/css/bootstrap.min.css"
],
"scripts": [
    "node_modules/jquery/dist/jquery.min.js",
    "node_modules/bootstrap/dist/js/bootstrap.min.js"
]

选项二

ng-bootstrap 包含一组基于 Bootstrap 标记和 CSS 的本机 Angular 指令。因此,它不依赖于 jQuery 或 Bootstrap 的 JavaScript。

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

安装完成后,将其导入到您的根模块中,并在@NgModule的“imports”数组中注册它。

import {NgbModule} from '@ng-bootstrap/ng-bootstrap';
@NgModule({
    declarations: [AppComponent, ...],
    imports: [NgbModule.forRoot(), ...],
    bootstrap: [AppComponent]
})

ng-bootstrap需要在您的项目中添加Bootstrap 4的css。您需要通过以下方式显式安装它:

npm install bootstrap@4  --save 

在你的 angular.json 文件中,在构建目标下的 styles 数组中添加文件路径。
"styles": [
    "src/styles.css",
    "node_modules/bootstrap/dist/css/bootstrap.min.css"
],

7

在 Angular 6 / 7 / 8 中,Bootstrap无法正常工作

我尝试了大多数网上的解决方案,但都没有用

只有下面的代码对我有效

无需更改angular.json文件

直接将以下行添加到style.css文件中

@import "../node_modules/bootstrap/dist/css/bootstrap.css"

因为在angular.json中我们已经提供了对style.css的引用


1
记住,如果 ng serve 正在运行,请停止服务器以使 angular.json 文件中的更改生效。

0

您可以将此路径放入`angular.json`文件中的样式标签内,例如:`"styles": ["./node_modules/bootstrap/dist/css/bootstrap.min.css"]`。


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