概述
在組件交互中,組件之間的鑲嵌一般有兩種方式:
- 在創建父組件時將子組件直接寫在模版中。
- 子組件通過投影方式嵌入父級組件,通過
ng-content
形式。
在這兩種情況下,如果我們需要訪問子組件的公開屬性或方法,就需要使用 @ViewChild
與 @ContentChild
裝飾器了。他們依次代表上面的兩種情況,具體使用如下。
實例
對于第一種(@ViewChild()
):
// template
<app-list></app-list>
// ts
// 父組件
@Component({
selector: 'app-list',
// 子組件,定義在組件內
template: `
<app-list-item></app-list-item>
`
})
export class ListComponent implements OnInit {
// 通過 @ViewChild 裝飾器聲明子組件
@ViewChild(TreeListComponent) listItem: TreeListComponent;
// 在 OnInit 階段獲取子組件的實例
ngOnInit() {
// 即這里可以使用子組件實例公開的變量與方法
console.log(this.listItem);
}
}
第二種形式(@ContentChild()
):
// template
<app-list>
<app-list-item></app-list-item>
</app-list>
// ts
// 父組件
@Component({
selector: 'app-list',
// 子組件,通過投影方式嵌入
template: `
<ng-content></ng-content>
`
})
export class ListComponent implements OnInit {
// 通過 @ContentChild 裝飾器聲明嵌入的組件
@ContentChild(TreeListComponent) listItem: TreeListComponent;
// 在 OnInit 階段獲取子組件的實例
ngOnInit() {
// 即這里可以使用嵌入的組件實例公開的變量與方法
console.log(this.listItem);
}
}
注意:如果需要子組件的實例,需在 OnInit 階段及之后才能獲取到。