如果我有一个组件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中试图解决这个问题的地方。
发布于 2019-08-04 06:27:18
我几乎忘记了尝试让它工作,但有一天晚上,我突然在一个梦中找到了答案。
在基础组件中,我们可以将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
发布于 2019-01-25 08:38:11
您所做的非常有趣,但我认为内容投影无法工作,因为<ng-content>在组件级别工作,而不是在模板级别工作。
它不会“产生”内容,而只是将现有内容投影或移动到组件中。
因此,投影内容的生命周期被绑定到声明它的位置,而不是显示它的位置,因此不能使用模板,模板可以在运行时多次实例化。
查看这个other question和这个article。
然而,我没有找到任何来自angular的官方文档。
https://stackoverflow.com/questions/54338938
复制相似问题