@ViewChild和@ContentChild有什么区别?
Angular 2提供了@ViewChild , @ViewChildren , @ContentChild和@ContentChildren装饰器来查询组件的后代元素。 前两者和后两者有什么不同?
我将使用Shadow DOM和Light DOM术语来回答你的问题(它来自Web组件,请看这里 )。 一般来说:
- Shadow DOM – 是由您 (作为组件的创build者 )定义并隐藏于最终用户的组件的内部DOM。 例如:
@Component({ selector: 'some-component', template: ` <h1>I am Shadow DOM!</h1> <h2>Nice to meet you :)</h2> <ng-content></ng-content> `; }) class SomeComponent { /* ... */ }
- Light DOM – 是组件的最终用户提供给您的组件的DOM。 例如:
@Component({ selector: 'another-component', directives: [SomeComponent], template: ` <some-component> <h1>Hi! I am Light DOM!</h1> <h2>So happy to see you!</h2> </some-component> ` }) class AnotherComponent { /* ... */ }
所以,你的问题的答案很简单:
@ViewChildren和@ContentChildren之间的区别是@ViewChildren在Shadow DOM中查找元素,而@ContentChildren在Light DOM中查找它们。
顾名思义, @ContentChild和@ContentChildren查询将返回@ContentChildren的<ng-content></ng-content>元素中的@ViewChild ,而@ViewChild和@ViewChildren仅直接查看视图模板上的元素。
这个来自Angular Connect的video有关于ViewChildren,ViewChild,ContentChildren和ContentChild的优秀信息https://youtu.be/4YmnbGoh49U
@Component({ template: ` <my-widget> <comp-a/> </my-widget> ` }) class App {} @Component({ selector: 'my-widget', template: `<comp-b/>` }) class MyWidget {}
从my-widget的angular度来看, comp-a是ContentChild , comp-b是ViewChild 。 CompomentChildren和ViewChildren返回一个迭代,而xChild返回一个实例。