【问题标题】:Angular2 router-outlet outputs component into ng-componentAngular2 router-outlet 将组件输出到 ng-component
【发布时间】:2017-10-05 10:07:15
【问题描述】:

在 Angular2 应用程序中,我使用 Bootstrap 的网格。 模块主组件的模板提供了一个网格的行:

<div class="row">
    <router-outlet></router-outlet>
</div>

并且子组件有 Bootstrap 的网格列:

<div class="col-md-8">Hello, world!</div>
<div class="col-md-4"></div>

问题是Angular2生成这样一个HTML:

<div class="row">
    <router-outlet></router-outlet>
    <ng-component>
        <div class="col-md-8">Hello, world!</div>
        <div class="col-md-4"></div>
    </ng-component>
</div>

所以:它添加了一个 ng-component 标签,它破坏了 Bootstrap 所需的结构(column block 必须是 row block 的子元素)。

如何防止生成 ng-component 标签?

【问题讨论】:

  • 那你是怎么解决的?
  • 你是怎么解决这个问题的?
  • 尚未解决:使用了不同的标记。
  • 如果使用ng-container 而不是ng-component,就不会出现这个问题。 AFAIK ng-component 仅供内部使用,但很容易混淆它们。但你没有说你实际使用的是什么库。
  • caniuse.com/css-display-contents 是理论上的解决方案

标签: twitter-bootstrap angular2-template angular2-directives router-outlet


【解决方案1】:

这是因为 .row 类而发生的。它有一个display:flex 的属性,它是一个弹性项目的容器。

在这种情况下,&lt;ng-componet&gt; 现在变成了一个弹性项目,并开始拥有弹性项目的默认属性。

我建议你现在改变你的 HTML 结构,也许引导团队会解决这个问题。

要获取有关默认属性弹性项目的更多信息,您可以单击here

【讨论】:

  • 确实问题出在柔性显示屏上。但是,我无法更改我的结构,因为我正在使用一些 UI 库。
【解决方案2】:

这是自动发生的,angular在router-outlet之后生成ng-component,与使用css flex无关。

ng-component 是注入元素的默认标签名称,如果没有给出另一个指令。如此处所述https://stackoverflow.com/a/57702912/4320602

来自https://medium.com/angular-in-depth/angular-router-series-secondary-outlets-primer-139206595e2

<router-outlet></router-outlet>
<ng-component>Routed components go here</ng-component>

从技术上讲,路由器会将路由组件放置在路由器出口之后的元素内。这会自动发生,因此您实际上不需要输入元素。

更多信息在这里: https://www.bennadel.com/blog/3350-routable-view-components-don-t-need-selectors-in-angular-4-4-4---but-they-may-be-helpful.htm

也许解决办法是:

<router-outlet></router-outlet>

并且子组件有 Bootstrap 的网格列:

  <div class="row">
    <div class="col-md-8">Hello, world!</div>
    <div class="col-md-4"></div>
  </div

所以 Angular 会生成这个 HTML:

    <router-outlet></router-outlet>
    <ng-component>
      <div class="row">
        <div class="col-md-8">Hello, world!</div>
        <div class="col-md-4"></div>
      </div>
    </ng-component>

【讨论】:

    【解决方案3】:

    将您的&lt;div class="rows"&gt; 包裹在路由器插座中

    <router-outlet> <div class="rows">...</div> </router-outlet>
    

    考虑到&lt;div class="rows"&gt;是从另一个文件夹外包的

    【讨论】:

      【解决方案4】:

      不,这是不可能的,它不应该影响你的风格。

      【讨论】:

      • 嗯,它确实会影响我的样式 :( 如果通过 Chrome 开发工具,我将 ng-component 的内容移动到 ng-component 之外 - 网格开始表现应有的行为。ng-component 肯定会中断布局。
      • 没有。它确实破坏了我的布局。
      猜你喜欢
      • 2017-05-18
      • 2020-11-23
      • 2016-03-25
      • 2017-12-29
      • 1970-01-01
      • 2017-03-28
      • 2017-02-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多