【问题标题】:Angular component inside of router-outlet on child route will not fill available space子路由上的路由器插座内的角组件不会填充可用空间
【发布时间】:2023-03-06 17:23:01
【问题描述】:

当导航到 '/child' 路由时,我的应用程序的根 <router-outlet></router-outlet> 将在子模块中显示以下组件:

child.component.ts

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

@Component({
  template: `
    <div style="display:flex; width: 100%; height: 100%;">
      <custom-sidebar-component></custom-sidebar-component>
      <router-outlet></router-outlet>
    </div>`
})
export class ChildComponent {
}

现在这个组件显示得很好,并按我的预期填满了整个屏幕。但是,当我尝试导航到该模块的子路径时,例如“/child/home”,我希望在上面的组件模板中看到的子 &lt;router-outlet&gt;&lt;/router-outlet&gt; 中显示以下 HTML。

child-home.component.html

<style>
  .parent-style {
    display: flex;
    flex-flow: row wrap;
    width: 100%;
    height: 100%;
  }

  .box-style {
    display: flex;
    justify-content: center;
    align-items: center;
    flex-grow: 1;
    background: red;
    color: white;
    border: 1px solid black;
  }
</style>
<div class="parent-style">
  <div class="box-style">Box 1</div>
  <div class="box-style">Box 2</div>
</div>

但是这次路由器插座的内容并没有像我希望的那样填满可用空间。我能够看到我想要的结果的唯一方法是打开开发工具并编辑包装我的组件的 Angular 生成的 _nghost 属性。如何让我的组件填满可用空间?

这是我所期望的

这是我实际得到的

【问题讨论】:

    标签: angular angular2-routing angular2-template angular-routing angular2-components


    【解决方案1】:

    那是因为渲染的 DOM 如下:

    <app-child  _nghost-c1="">
    <div _ngcontent-c1="" class="parent-style">
    <div _ngcontent-c1="" class="box-style">Box 1</div>
    <div _ngcontent-c1="" class="box-style">Box 2</div></div>
    </app-child>
    

    所以解决方法很简单,给宿主元素添加一些样式,你可以使用host:{'class':'foo'}或者直接在你的ChildComponent的@Component{}中添加host:{'style':'width:100%'}

    【讨论】:

    • 如此简单,确实解决了我的问题。我对阴影 dom 元素的样式不熟悉,感谢您提供的信息!今天我学会了。
    • 感谢您的回答,除了在每个子元素中设置宿主元素的样式之外,还有其他解决方案吗?
    猜你喜欢
    • 1970-01-01
    • 2017-04-29
    • 2021-03-13
    • 2017-10-27
    • 2021-11-07
    • 2017-02-15
    • 1970-01-01
    • 2018-07-28
    • 2023-04-01
    相关资源
    最近更新 更多