如何在Angular中使用内容投影(又称翻译)

时间:2017-08-18 09:06:15

标签: angular angular-components

我是角色4的新手。

我对角度4嵌入式组件有疑问。

示例:

<hero-list>
    <hero></hero>
    <hero></hero>
</hero-list>

我想知道如何基于这个将组件嵌入到另一个组件中的结构来创建视图。

2 个答案:

答案 0 :(得分:7)

您应该在<ng-content></ng-content> - 组件中使用hero-list。所以你可以实现上面的愿望。

<强>英雄list.component.html

<div class="hero-list">
  <h1>Hero list</h1>
  <ng-content></ng-content>
</div>

现在您可以打包hero-item - 组件,它们将打印在hero-list组件内。

<强> app.component.html

<hero-list>
  <hero-item></hero-item>
  <hero-item></hero-item>
</hero-list>

以下是工作示例:https://stackblitz.com/edit/angular-nvpmtc

here是关于angualr内容投影的好文章。

答案 1 :(得分:1)

如果您的意思是想要一个包含子视图的主布局,您可能需要查看Angular路由器https://angular.io/tutorial/toh-pt5

可能看起来像这样

<app-component>
  <h1>Static title</h1>
  <router-outlet></router-outlet>
</app-component>

当导航到不同的链接时,路由器插座将在路由文件中定义的不同组件之间切换,但它周围的html不会改变