ViewChild
官方文档翻译
先来看看官方解释
- 声明一个对子元素的引用。
ViewChild
需要一个参数来选择元素。- 如果参数是一个类型,一个指令或一个类型的组件将被绑定。
- 如果参数是一个字符串,字符串被解释为一个选择器。也就是一个元素包含模板变量(如
#child
)。 - 在任何情况下,如果找到多个元素,那么只返回第一个。
- 这个子元素将在
ngAfterViewInit()
回调前被赋值。
笔者英语已经还给体育老师,各位看官将就着,自己理解一下。
不理解吗?
不理解吗?好吧,怪我,我用最通俗的东北话大概讲解下。
ViewChild
就是选择元素用的。- 你不告诉它选择什么元素,它肯定不知道啊!所以你得给一个类型。
ViewChild
这个兄弟还算讲究,你不告诉它类型可以,那就给他一个模板变量名。(下面会解释)- 如果这位仁兄找到了好多元素,那么它只会返回第一个找到的元素。
ViewChild
会在ngAfterViewInit()
回调函数之前做完工作,也就是说你不能在构造函数中使用这个元素。
更通俗一些
下面我将用程序员最直接的方式,帮助大家理解:
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
好了,估计你已经知道基本的使用方式了
@ViewChild(MyCom)
可以获取到页面中的MyCom类型的组件@ViewChild('myCom')
可以获取到被标记为#myCom
的组件
ContentChild
点击这里查看官方解释
官方文档翻译
- 查询一个内容。
- 内容查询结果将在
ngAfterContentInit()
回调前完成
不是我偷懒没翻译全,官方就这两句话。这尼玛是甲骨文啊?什么叫查询一个内容
?
好在凭借我多年的学习和吹牛逼经验,在stackoverflow同志网站上找到了相关问题和解答
理解ContentChild
补充ViewChildren
@ViewChildren
跟@ViewChild
实际上没什么区别,从名字上很容易理解,一个获取一堆子元素,一个获取一个子
元素。
@ViewChild(MyCom)
返回的是一个MyCom
变量@ViewChildren(MyCom)
返回的是一个QueryList<MyCom>
为什么突然蹦出个ViewChildren?因为下面老外使用它来解释的
老外的解释
stackoverflow上某老外这样解释
The difference between @ViewChildren and @ContentChildren is that @ViewChildren look for elements in Sh
adow DOM while @ContentChildren look for them in Light DOM.
我在用中文翻译下哈
@ViewChildren
和@ContentChildren
之间的区别在于,@ViewChildren
用于Shadow DOM,而@ContentC
hildren
用于Light DOM
卧槽,Shadow DOM
是什么?Light DOM
又是什么? 这里有准确的答案
不完全解答
咦?如果你的基础较好的话,把ContentChildren
这个两个单词分开,content-children
好像似曾相识的感觉。
想起没?ng-content
!
笔者理解:
ContentChild
用来获取<ng-content></ng-content>
中的元素
我们写个伪代码实践下:
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
最终输出:
- 1
- 2
- 3
- 4
然后我们调试后发现,this.viewCom
等于第一行<h1/>
,this.contentView
等于第二行<h1/>