![](/img/trans.png)
[英]What are all the valid selectors for ViewChild and ContentChild?
[英]What's the difference between @ViewChild and @ContentChild?
Angular 2 提供了@ViewChild
、 @ViewChildren
、 @ContentChild
和@ContentChildren
装饰器,用于查询组件的后代元素。
前两者和后两者有什么区别?
我将使用Shadow DOM和Light DOM术语回答您的问题(它来自 Web 组件,请在此处查看更多信息)。 一般来说:
@Component({
selector: 'some-component',
template: `
<h1>I am Shadow DOM!</h1>
<h2>Nice to meet you :)</h2>
<ng-content></ng-content>
`;
})
class SomeComponent { /* ... */ }
@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
寻找在阴影DOM元素,同时@ContentChildren
寻找他们光在DOM。
顾名思义, @ContentChild
和@ContentChildren
查询将返回@ContentChildren
的<ng-content></ng-content>
元素中存在的指令,而@ViewChild
和@ViewChildren
只直接查看视图模板上的元素.
来自 Angular Connect 的这段视频提供了关于 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
的角度来看, comp-a
是ContentChild
, comp-b
是ViewChild
。 CompomentChildren
和ViewChildren
返回一个可迭代对象,而 xChild 返回单个实例。
让我们举个例子,我们有一个主组件和一个子组件,内部子组件有一个小子组件。
<home>
<child>
<small-child><small-child>
</child>
</home>
现在您可以使用@viewChildren 获取 home 组件上下文中的所有子元素,因为它们是直接添加到 home 组件的模板中的。 但是,当您尝试从子组件的上下文访问<small-child>
元素时,您将无法访问它,因为它没有直接添加到子组件模板中。 它是通过内容投影由主组件添加到子组件中的。 这是@contentChild 的用武之地,您可以使用@contentChild 来获取它。
当您尝试访问控制器中的元素引用时会出现差异。 您可以访问通过@viewChild 直接添加到组件模板中的所有元素。 但是您无法使用@viewChild 获取投影元素引用要访问投影元素,您必须使用@contentChild。
只需将 ViewChildren 重命名为 InternalChildren,将 ContentChildren 重命名为 ExternalChildren
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.