【问题标题】:How to render child component with bootstrap styles applied correctly?如何正确应用引导样式来渲染子组件?
【发布时间】:2019-12-10 09:05:45
【问题描述】:

引导程序 css 未正确设置我的辅助 Angular 组件的样式 when the selector is embedded in app.component.html.我正在使用 ng-bootstrap 通过在默认的 angular8 项目之后包含它 使用ng new myapp创建的

我使用 Angular CLI 生成了一个新应用程序:ng new my-new-app。然后 已安装ng-bootstrapapp.component.html 中,我包含了指令:app-child 和 组件已成功包含,但它没有被引导程序设置样式。 当我直接在 app.component.html 中转储代码时(不使用 应用子指令;它已被注释掉)引导样式是 申请成功。 似乎带有引导程序的app-child 组件 应用了bootstrap 样式后,样式无法正确呈现。

app.component.html 中的任何位置,包括子组件

<div class="container content">
   <div class="row">
     <app-child-left></app-child-left>

     <app-child-right></app-child-right>
   </div>
</div>

app-child-left 包含:

<div class="col-md-6">
   Child LEFT
</div>

app-child-right 包含:

<div class="col-md-6">
   Child RIGHT
</div>

我希望 Div 被正确插入并且 Bootstrap 呈现 child-left,向左,child-right,向右。

实际结果是左侧的一大块文本。

编辑: 这是我的 angular.json 文件。

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

此配置有效,这可能是一个错误吗?将 div class=row 带入子项将导致 html 和样式正确呈现:

app.component.html

<div class="container content">
  <!--div class="row"-->

    <app-child-left></app-child-left>

    <!-- app-child-right></app-child-right-->

  <!-- /div -->
</div>

child-left.component.html:

<!--div class="col-md-6">
        Child LEFT:
      </div -->

      <div class="row">
        <div class="col-md-6">
          Child LEFT
        </div>
        <div class="col-md-6">
          Child RIGHT
        </div>
   </div>

【问题讨论】:

  • 您是否为子模块导入了import {NgbModule} from '@ng-bootstrap/ng-bootstrap';?你的app.module 怎么样?
  • 你是否在标签 styles 中添加了 angular.json 在 "src/styles.css" 之前的 bootstrap.css 或 bootstrap.css.min?,请参阅angular.io/guide/workspace-config#style-script-config .请记住,您不需要下载所有引导程序,否则只需下载 bootstrap.min.css
  • 我假设 OP 有,因为 OP 提到他能够看到样式。
  • @nicraft my app.module 导入 NgbModule 以及 ChildLeftComponent 和 ChildRightComponent。在声明中列出了 ChildLeftComponent 和 ChildRightComponent。

标签: angular ng-bootstrap


【解决方案1】:

您还需要将 Bootstrap 4 CSS 添加到您的应用程序才能使用 ngxBootstrap。

您可以使用 npm 安装:npm i bootstrap;并包含到您的angular.json 如下:

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

您只需要 CSS,不应该添加其他 JavaScript 依赖项 像 bootstrap.js、jQuery 或 popper.js 一样 ng-bootstrap 的目标是 完全替换它们。

【讨论】:

  • @nicraft in angular.json.. 在架构师下。样式:[“src/styles.scss”,{“输入”:“./node_modules/bootstrap/dist/css/bootstrap.css”}]
  • 无需输入,只需在 styles.scss 路径后添加"node_modules/bootstrap/dist/css/bootstrap.min.css"为你更新了我的答案
  • 因为重新启动,我们需要在 angular.json 中首先放置引导程序——这个顺序就是它被应用的原因。我还进行了另一次更新 - 这可能是一个错误 - 但是当您将 class=row 的 div 带入左孩子并将其从 app.component.html 中删除时,一切正常。