大佬教程收集整理的这篇文章主要介绍了Angular2中ViewChild与ContentChild的区别,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
先来看看官方解释
ViewChild
需要一个参数来选择元素。#child
)。ngAfterViewInit()
回调前被赋值。笔者英语已经还给体育老师,各位看官将就着,自己理解一下。
不理解吗?好吧,怪我,我用最通俗的东北话大概讲解下。
ViewChild
就是选择元素用的。ViewChild
这个兄弟还算讲究,你不告诉它类型可以,那就给他一个模板变量名。(下面会解释)ViewChild
会在ngAfterViewInit()
回调函数之前做完工作,也就是说你不能在构造函数中使用这个元素。下面我将用程序员最直接的方式,帮助大家理解:
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);//@L_437_16@myCom对象
console.log(this.myComB);//@L_437_16@myCom对象
console.log(this.myComA == this.myComB);//true
}
}
好了,估计你已经知道基本的使用方式了
点击这里查看官方解释
不是我偷懒没翻译全,官方就这两句话。这尼玛是甲骨文啊?什么叫查询一个@L_674_25@
?
好在凭借我多年的学习和吹牛逼经验,在stackoverflow同志网站上找到了相关问题和解答
@ViewChildren
跟@ViewChild
实际上没什么区别,从名字上很容易理解,一个获取一堆子元素,一个获取一个子元素。
为什么突然蹦出个ViewChildren?因为下面老外使用它来解释的
stackoverflow上某老外这样解释
我在用中文翻译下哈
卧槽,Shadow DOM
是什么?Light DOM
又是什么? 这里有准确的答案
咦?如果你的基础较好的话,把ContentChildren
这个两个单词分开,content-children
好像似曾相识的感觉。想起没?ng-content
!
我们写个伪代码实践下:
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>
然后我们调试后发现,this.viewCom
等于第一行<h1/>
,this.contentView
等于第二行<h1/>
这也证实了我的理解。
欢迎拍砖
以上是大佬教程为你收集整理的Angular2中ViewChild与ContentChild的区别全部内容,希望文章能够帮你解决Angular2中ViewChild与ContentChild的区别所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。