Angular 2提供@ViewChild,@ViewChildren,@ContentChild和@ContentChildren装饰器,用于查询组件的后代元素。前两者和后两者有什么区别?
我将使用Shadow DOM和Light DOM术语来回答您的问题(它来自Web组件,参见
here)。一般来说:
> Shadow DOM – 是您的组件的内部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 { /* ... */ }
所以,你的问题的答案很简单:
The difference between
@ViewChildren
and@ContentChildren
is that@ViewChildren
look for elements in Shadow DOM while@ContentChildren
look for them in Light DOM.