<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>
不產生內容,它不僅是項目它(作品爲其中兒童被你的組件模板中顯示的placehoder。
儘管*ngFor
會生成3 <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
。目前正在進行一個更好的方法的工作(ngTemplateOutlet
https://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
又見How to repeat a piece of HTML multiple times without ngFor and without another @Component更多ngTemplateOutlet
Plunker例子。
更新角5
ngOutletContext
更名爲ngTemplateOutletContext
參見https://github.com/angular/angular/blob/master/CHANGELOG.md#500-beta5-2017-08-29
很可能才達到這一點,但它僅僅是太多的工作,你可以得到非常接近例如[這裏](http://stackoverflow.com/questions/36730210/binding-events-when-using-a-ngfortemplate-in-angular-2/36732644?noredirect=1#comment61052816_36732644) – kemsky