ViewChildren 和 ContentChildren 還有 Viewchild
angular2 中的component有兩種
Shadow DOM
這是一種內部的DOM,由用戶在@Component中定義。在以下代碼中some-component就是ViewChild。
@Component({
selector: 'some-component',
template: `
<h1>I am Shadow DOM!</h1>
<h2>Nice to meet you :)</h2>
<ng-content></ng-content>
`;
})
class SomeComponent { /* … */ }
Light DOM
light DOM是由最終用戶使用,比如下面代碼中的some-component就可被ContentChild獲取到。
@Component({
selector: 'another-component',
directives: [SomeComponent],
template: `
<some-component>
<h1>Hi! I am Light DOM!</h1>
<h2>So happy to see you!</h2>
</some-component>
`
})
class AnotherComponent { /* ... */ }
而 ViewChildren
和 ContentChildren
可用於獲取多個實例,例:
import {Component,ContentChildren,QueryList,AfterContentInit} from 'angular2/core';
import {ChildComponent} from './child';
@Component({
selector: 'my-parent',
template: `
<div>Parent Component</div>
<p *ngFor="#child of childs;#i=index">{{child.name}}-{{i}}</p>
`
})
export class ParentComponent implements AfterContentInit{
@ContentChildren(ChildComponent)
childs:QueryList<ChildComponent>; // 通過QueryList將多個內部component實例包裹起來。
ngAfterContentInit() {
console.log(this.childs)
}
}