<ng-content>
要将内容投影到元素(嵌入),您需要 <ng-content> 元素,例如
@Component({
selector: 'parent',
directives: [ChildComponent], // needed?
template: `
<h1>{{title}}</h1>
<ul>
<li *ngFor="letchild of children()">
<ng-content></ng-content>
</li>
</ul>`
})
<ng-content select="xxx">
但这不适用于您的用例,因为<ng-content> 不会产生内容,它只会投影它(用作在组件模板中显示子项的占位符。
尽管*ngFor 会产生3 个<ng-content> 元素,但子元素只会在第一个<ng-content> 元素中显示一次。
<ng-content> 允许使用选择器,如
<ng-content select="[name=Chris]"></ng-content>
模板在哪里
<ul>
<li>
<ng-content select="[name=Chris]"></ng-content>
</li>
</ul>`
会导致
<h1>Welcome</h2>
<ul>
<li><b>Chris</b> is on the Blue Team</li>
</ul>
Binding events when using a ngForTemplate in Angular 2 中解释的更灵活和强大的方法(来自@kemsky 的评论)
<template>、@ViewChildren() 和 *ngForTemplate
如果您将子项包装在<template> 标记中,您可以使用@ContentChildren() 访问它们,并使用*ngFor 和*ngForTemplate 插入它们。
我在这里使用了内部*ngFor 的小技巧。有一种更好的方法正在进行中(ngTemplateOutlethttps://github.com/angular/angular/pull/8021 已合并)
@Component({
selector: 'parent',
template: `
<h1>{{title}}</h1>
<ul>
<li *ngFor="let child of templates">
<!-- with [child] we make the single element work with
*ngFor because it only works with arrays -->
<span *ngFor="let t of [child]" *ngForTemplate="child"></span>
</li>
</ul>
<div>children:{{children}}</div>
<div>templates:{{templates}}</div>
`
})
export class ParentComponent {
@Input() title;
@ContentChildren(TemplateRef) templates;
}
@Component({
selector: 'my-app',
directives: [ParentComponent],
template: `
<h1>Hello</h1>
<parent title="Welcome">
<template><child name="Chris">Blue Team</child></template>
<template><child name="Tom">Red Team</child></template>
</parent>
`,
})
export class AppComponent {}
Plunker example
有关更多ngTemplateOutlet Plunker 示例,另请参阅How to repeat a piece of HTML multiple times without ngFor and without another @Component。
更新 Angular 5
ngOutletContext 更名为ngTemplateOutletContext
另见https://github.com/angular/angular/blob/master/CHANGELOG.md#500-beta5-2017-08-29