iT邦幫忙

0

Angular 中 @ViewChild 与 @ContentChild 的区别

概述

在组件交互中,组件之间的镶嵌一般有两种方式:

  1. 在创建父组件时将子组件直接写在模版中。
  2. 子组件通过投影方式嵌入父级组件,通过 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 阶段及之后才能获取到。


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
yutao116
iT邦新手 5 級 ‧ 2019-05-09 09:21:44

我公司也是用的angular7

看更多先前的回應...收起先前的回應...
YuJinpan iT邦新手 5 級 ‧ 2019-05-09 17:36:13 檢舉

/images/emoticon/emoticon34.gif

yutao116 iT邦新手 5 級 ‧ 2019-05-10 16:40:45 檢舉

很孤单

YuJinpan iT邦新手 5 級 ‧ 2019-05-11 10:10:38 檢舉

不行,应该要孤傲/images/emoticon/emoticon08.gif

yutao116 iT邦新手 5 級 ‧ 2019-05-11 21:39:09 檢舉

加我微信 yutao520u 如果可以的话/images/emoticon/emoticon13.gif

我要留言

立即登入留言