Angular 中 @ViewChild 與 @ContentChild 的區(qū)別

概述

在組件交互中,組件之間的鑲嵌一般有兩種方式:

  1. 在創(chuàng)建父組件時將子組件直接寫在模版中。
  2. 子組件通過投影方式嵌入父級組件,通過 ng-content 形式。

在這兩種情況下,如果我們需要訪問子組件的公開屬性或方法,就需要使用 @ViewChild@ContentChild 裝飾器了。他們依次代表上面的兩種情況,具體使用如下。

實例

對于第一種(@ViewChild()):


// template
<app-list></app-list>

// ts
// 父組件
@Component({
    selector: 'app-list',

    // 子組件,定義在組件內(nèi)
    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 階段及之后才能獲取到。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容