Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

angular - using ng-content in ng-template

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>

The above code does just render World ! :(

Here is the live example

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

Just Browsing Browsing

2.1m questions

2.1m answers

60 comments

57.0k users

...