如何将ng-content放入模板

时间:2019-01-24 03:23:48

标签: angular

如果我的组件BaseComponent看起来像

<ng-container *ngTemplateOutlet="tpl"></ng-container>

和另一个将模板传递到其中的组件OtherComponent

<base-component [tpl]="tpl">Some content for ng-content</base-component>

<ng-template #tpl>
  <ng-content></ng-content>
  <!-- How do I get access to ng-content passed to the base component instead of other component? --> 
</ng-template>

我能否获得传递到暴露在模板中的组件中的ng-content?

我要实现的目标是在应用程序的其他位置定义一个模板,该模板可以定义组件应将内容投射到模板中的位置。

有关这个问题的更多信息,请参见Use configurable templates in Angular,以及我在StackBlitz https://stackblitz.com/edit/angular-lj3x1f中尝试解决该问题的位置。

2 个答案:

答案 0 :(得分:0)

您正在做的事情很有趣,但是我认为内容投影无法工作,因为<ng-content>在组件级别而不是模板级别工作。

它不“产生”内容,而只是将现有内容投影或移动到组件中。

因此,投影内容的生命周期绑定到声明的位置,而不是显示的位置,因此无法与模板一起使用,模板可以在运行时多次实例化。

请参阅此other question和此article

但是我没有从angular找到任何官方文档。

答案 1 :(得分:0)

我几乎忘了试图使它正常工作,但答案却在前夜的梦里突然出现。

在基本组件中,我们可以将ng-content放入模板中,然后将该模板传递给用户定义的模板上下文。

<ng-container *ngTemplateOutlet="tpl;context:{ $implicit: contentTemplate }">
</ng-container>

<ng-template #contentTemplate>
  <ng-content></ng-content>
</ng-template>

然后,当我们定义要传递给基本组件的模板时,可以在上下文中使用该模板来显示ng-content。

<base-component [tpl]="tpl">Some content for ng-content</base-component>

<ng-template #tpl let-contentTemplate>
  <ng-template *ngTemplateOutlet="contentTemplate"></ng-template>
</ng-template>

这是一个StackBlitz

https://stackblitz.com/edit/angular-tvqjgv