ng-bootstrap在Angular 4中无法正常工作

18

我刚开始学习Angular 4,尝试配置Bootstrap。 我已经安装了ng-bootstrap:

https://ng-bootstrap.github.io/#/getting-started

我按照页面上的步骤进行了所有操作,但是我的页面上没有看到Bootstrap效果。 这是我的代码:

src/app/app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { FormsModule } from '@angular/forms';
import {NgbModule} from '@ng-bootstrap/ng-bootstrap';

@NgModule({
  declarations: [
    AppComponent
  ],
imports: [
   BrowserModule,
   FormsModule,  // add  this
   NgbModule.forRoot()
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

src/app/app.component.html

->

src/app/app.component.html

<div class="container">

<h1 class="text-primary">{{title}} </h1>

<h2 class="text-primary">My Heroes</h2>
<ul class="heroes">
  <li *ngFor="let hero of heroes"
    [class.selected]="hero === selectedHero"
    (click)="onSelect(hero)">
    <span class="badge">{{hero.id}}</span> {{hero.name}}
   </li>
</ul>

<div class="alert alert-success" role="alert">
 <strong>Well done!</strong> You successfully read this important alert 
   message.
</div>

<div *ngIf="selectedHero">
  <h2>{{selectedHero.name}} details!</h2>
<div><label>id: </label>{{selectedHero.id}}</div>
<div>
  <label>name: </label>
  <input [(ngModel)]="selectedHero.name" placeholder="name"/>
</div>

我也试过在index.html中添加一些代码,但它没有起作用,

对于这行代码,我希望能看到一些颜色:

<h1 class="text-primary">{{title}} </h1>

我在检查HTML头部时没有找到任何Bootstrap的引用。 有帮助的话,请帮忙解决一下? 谢谢

2个回答

46
在你提到的页面中,ng-bootstrap提到需要Bootstrap CSS作为依赖项。因此,需要单独加载它。
如果你使用Angular CLI创建应用程序,你可以按照这个官方指南添加它。
更新:
如评论中所述,将CSS添加到.angular-cli.json中的styles(或对此文件的任何其他更改)将要求您重新启动ng serve或ng build --watch(如果其中一个已在运行)。
更新2(当前推荐方法):
对于Angular 6及以上版本,你可以使用这个解决方案。
转到styles.css并添加这一行。
@import "~bootstrap/dist/css/bootstrap.css";

另请参阅此项技术的内部工作原理:

https://blog.angularindepth.com/this-is-how-angular-cli-webpack-delivers-your-css-styles-to-the-client-d4adf15c4975


2
非常感谢,我需要重新启动ng serve,现在它正常工作了!谢谢 - MarcosF8
1
谢谢,对我来说以下代码有效: @import "../node_modules/bootstrap/dist/css/bootstrap.css"; - Stalli
对于 Angular 6 及更高版本,您可以使用此解决方案。转到 styles.css 并添加以下行:@import "~bootstrap/dist/css/bootstrap.css"; 它的效果很棒。 - Avinash Khadsan
是的,这就是2018年9月更新2推荐的方法。我让它更加明确,这是推荐的方法。谢谢。 - Meligy

1
我看不到你的代码中有任何 ng-bootstrap 组件!我认为你正在寻找 Bootstrap 样式,这也是使用 ng-bootstrap 的前提条件。
将以下行添加到 index.html 文件的 <head></head> 标签之间:
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

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