【问题标题】:Angular 2: Wrapping a component inside a parent componentAngular 2:将组件包装在父组件中
【发布时间】:2018-07-13 13:46:15
【问题描述】:

我正在尝试将组件放入父组件中,就像在 React 中一样。

反应示例:

父组件

<div>
  Hello from parent
  {this.props.children}
</div>

子组件

<ParentComponent>
  Hello from child
</ParentComponent>

基本上我要做的是在父标签之间包含子标签。

我想到了传递元素的@Input,但它听起来非常错误和丑陋。

【问题讨论】:

  • 您需要在 html 中使用组件的选择器。建议看官方教程:angular.io/tutorial/toh-pt1#show-the-heroescomponent-view
  • 我已经完成了教程。在另一个组件中包含一个组件,是的。但我希望将父组件包含在子组件中,并将子组件内容放置到父组件中的指定占位符。

标签: angular angular-components


【解决方案1】:

父组件:

<div>
  Hello from parent
  <ng-content select=".txt"></ng-content>
</div>

子组件:

<ParentComponent>
  <ng-container class="txt">
        Hello from child
    </ng-container>
</ParentComponent>

输出: 来自家长的问候 孩子问好

【讨论】:

  • 非常感谢。这就是我要找的东西!
【解决方案2】:

假设您的子组件有一个选择器,假设它被称为app-child,那么在父组件的 HTML 模板中您可以这样称呼它:

<div>
  Hello from parent
  <app-child></app-child>
</div>

现在,您在子组件的 HTML 中的所有内容都将按原样显示。此外,如果您需要将输入从父级传递给子级,您可以执行以下操作:

<div>
  Hello from parent
  <app-child [objInChild]="valFromParent"></app-child>
</div>

其中valFromParent 是父级可以提供的值,objInChild 是您在孩子的类组件中使用@Input 注释的对象(例如在文件child.component.ts 中)以接收传入的值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-15
    • 1970-01-01
    • 1970-01-01
    • 2017-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-07
    相关资源
    最近更新 更多