在ng-template中使用ng-content [英] using ng-content in ng-template

查看:172
本文介绍了在ng-template中使用ng-content的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在<ng-template>内使用<ng-content>(及其 select 选项),还是仅在组件内工作?

Is it possible to use <ng-content> (and its select option) inside a <ng-template> or does it only works within a component ?

<ng-container *ngTemplateOutlet="tpl">
  <span greetings>Hello</span>
</ng-container>

<ng-template #tpl>
  <ng-content select="[greetings]"></ng-content> World !
</ng-template>

上面的代码只是渲染World !:(

The above code does just render World ! :(

这是现场示例

推荐答案

据我所知,使用ng-content是不可能的,但是您可以为模板提供参数.因此,可以传递另一个NgTemplate,它可以再次与原始模板内的NgTemplateOutlet一起使用.这是一个工作示例:

As far as i know it is not possible using ng-content, but you can provide parameters to the template. So it's possible to pass another NgTemplate, which can again be used with an NgTemplateOutlet inside the original template. Here's a working example:

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

<ng-template #paramTemplate>
  <span>Hello</span>
</ng-template>


<ng-template #tpl let-param>
  <ng-container *ngTemplateOutlet="param"></ng-container> World !
</ng-template>

实际上甚至可以将多个模板传递给原始模板:

Actually it is even possible to pass multiple templates to the original template:

<ng-container *ngTemplateOutlet="tpl, context: {'param1': paramTemplate1, 'param2': paramTemplate2}">
</ng-container>

<ng-template #paramTemplate1>
  <span>Hello</span>
</ng-template>

<ng-template #paramTemplate2>
  <span>World</span>
</ng-template>


<ng-template #tpl let-param1="param1" let-param2="param2">
  <ng-container *ngTemplateOutlet="param1"></ng-container>
  <ng-container *ngTemplateOutlet="param2"></ng-container>
</ng-template>

这篇关于在ng-template中使用ng-content的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆