Angular2中ViewChild与ContentChild的区别
ViewChild官方文档翻译先来看看官方解释
笔者英语已经还给体育老师,各位看官将就着,自己理解一下。 不理解吗?不理解吗?好吧,怪我,我用最通俗的东北话大概讲解下。
更通俗一些下面我将用程序员最直接的方式,帮助大家理解: import {Component,ViewChild,AfterViewInit} from '@angular/core';
@Component({
selector: 'my-com',template: '<button>我是一个按钮</button>'
})
export class MyCom{
}
@Component({
template: '<my-com #myCom></my-com>'
directives: [MyCom]
})
export class MyPage implements AfterViewInit{
@ViewChild(MyCom) myComA;
@ViewChild('myCom') myComB;
public constructor(){
console.log(this.myComA);//undefined
console.log(this.myComB);//undefined
}
public ngAfterViewInit(){
console.log(this.myComA);//输出MyCom对象
console.log(this.myComB);//输出MyCom对象
console.log(this.myComA == this.myComB);//true
}
}
好了,估计你已经知道基本的使用方式了
ContentChild点击这里查看官方解释 官方文档翻译
不是我偷懒没翻译全,官方就这两句话。这尼玛是甲骨文啊?什么叫 好在凭借我多年的 理解ContentChild补充ViewChildren
为什么突然蹦出个ViewChildren?因为下面老外使用它来解释的 老外的解释stackoverflow上某老外这样解释
我在用中文翻译下哈
卧槽, 不完全解答咦?如果你的基础较好的话,把
我们写个伪代码实践下: import {Component,ContentChild} from '@angular/core';
/// 儿子组件
@Component({
selector: 'son-com',template: '<h1>im text</h1>',directives: [MyCom]
})
export class SonCom{
}
/// 爸爸组件
@Component({
selector: 'father-com',template: ' <son-com></son-com> <ng-content></ng-content> ',directives: [SonCom]
})
export class FatherCom implements AfterViewInit{
@ViewChild(SonCom) viewCom;
@ContentChild(SonCom) contentCom;
public ngAfterViewInit(){
console.log(this.viewCom);
console.log(this.contentCom);
}
}
最终输出: <father-com>
<h1>im text</h1>
<h1>im text</h1>
</father-com>
然后我们调试后发现, 这也证实了我的理解。 完结欢迎拍砖 参考文献Switching to Angular 2 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |