首页 > 解决方案 > 如何将 ng-content 放入模板

问题描述

如果我有一个看起来像的组件 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 ?

我想要实现的是在应用程序的其他地方定义一个模板,该模板能够定义组件应该将内容投影到模板中的位置。

更多关于我想要实现的目标可以在这个问题中看到,在 Angular 中使用可配置模板,以及我在这个 StackBlitz https://stackblitz.com/edit/angular-lj3x1f中试图解决这个问题的地方。

标签: angular

解决方案


我几乎忘记了试图让它发挥作用,但答案突然出现在我的梦中。

在基础组件中,我们可以将 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


推荐阅读