@ViewChild 和 @ContentChild 有什么区别? [英] What's the difference between @ViewChild and @ContentChild?
问题描述
Angular 2 提供了 @ViewChild
、@ViewChildren
、@ContentChild
和 @ContentChildren
装饰器,用于查询组件的后代元素.
Angular 2 provides @ViewChild
, @ViewChildren
, @ContentChild
and @ContentChildren
decorators for querying a component's descendant elements.
前两个和后两个有什么区别?
What's the difference between the first two and the latter two?
推荐答案
我将使用 Shadow DOM 和 Light DOM 术语(它来自网络组件,请参见此处).一般来说:
I'll answer your question using Shadow DOM and Light DOM terminology (it have come from web components, see more here). In general:
- Shadow DOM - 是组件的内部 DOM,由您定义(作为组件的创建者) 并对最终用户隐藏.例如:
- Shadow DOM - is an internal DOM of your component that is defined by you (as a creator of the component) and hidden from an end-user. For example:
@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.例如:
- Light DOM - is a DOM that an end-user of your component supply into your component. For example:
@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 { /* ... */ }
所以,你的问题的答案很简单:
So, the answer to your question is pretty simple:
@ViewChildren
和 @ContentChildren
的区别在于 @ViewChildren
在 Shadow DOM 中寻找元素,而 @ContentChildren代码> 在 Light DOM 中寻找它们.
The difference between
@ViewChildren
and@ContentChildren
is that@ViewChildren
look for elements in Shadow DOM while@ContentChildren
look for them in Light DOM.
这篇关于@ViewChild 和 @ContentChild 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!