[英]Angular2 child component as data
假設我有兩個組成部分: parent
和child
。 HTML將如下所示:
<parent title="Welcome">
<child name="Chris">Blue Team</child>
<child name="Tom">Red Team</child>
</parent>
最終輸出如下:
<h1>Welcome</h2>
<ul>
<li><b>Chris</b> is on the Blue Team</li>
<li><b>Tom</b> is on the Red Team</li>
</ul>
父組件:
@Component({
selector: 'parent',
directives: [ChildComponent], // needed?
template: `
<h1>{{title}}</h1>
<ul>
<li *ngFor="#child of children()">{{child.content}}<li>
</ul>`
})
export class ParentComponent {
@Input() title;
children() {
// how?
}
}
如何從父級中訪問子組件並獲取其內容?
此外,我不希望自動渲染孩子。 根據某些條件,我可能會選擇不顯示某些孩子。
謝謝。
<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>
在Angular 2中使用ngForTemplate時,在Binding事件中解釋了一種更靈活,更強大的方法(來自@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 {}
另請參閱如何在沒有ngFor的情況下多次重復HTML片段,如果沒有其他@Component , ngTemplateOutlet
可以獲得更多ngTemplateOutlet
Plunker示例。
更新Angular 5
ngOutletContext
已重命名為ngTemplateOutletContext
另見https://github.com/angular/angular/blob/master/CHANGELOG.md#500-beta5-2017-08-29
也許你正在尋找這個? https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#parent-to-child-local-var
您可以將本地var分配給父視圖中的任何子項
<child #child1></child>
<child #child2></child>
<button (click)="child1.doSomething()">Trigger child1</button>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.