@ViewChild和@ContentChild有什么区别?

角2提供@ViewChild@ViewChildren@ContentChild@ContentChildren用于查询一个组件的派生元素装饰器。

前两个和后两个有什么区别?


互换的青春
浏览 954回答 3
3回答

临摹微笑

我将使用Shadow DOM和Light DOM术语回答您的问题(它来自Web组件,请参见此处)。一般来说:影子DOM-是组件的内部DOM,由您定义(作为组件的创建者)并向最终用户隐藏。例如:@Component({&nbsp; selector: 'some-component',&nbsp; template: `&nbsp; &nbsp; <h1>I am Shadow DOM!</h1>&nbsp; &nbsp; <h2>Nice to meet you :)</h2>&nbsp; &nbsp; <ng-content></ng-content>&nbsp; `;})class SomeComponent { /* ... */ }轻型DOM-是组件的最终用户提供给组件的DOM。例如:@Component({&nbsp; selector: 'another-component',&nbsp; directives: [SomeComponent],&nbsp; template: `&nbsp; &nbsp; <some-component>&nbsp; &nbsp; &nbsp; <h1>Hi! I am Light DOM!</h1>&nbsp; &nbsp; &nbsp; <h2>So happy to see you!</h2>&nbsp; &nbsp; </some-component>&nbsp; `})class AnotherComponent { /* ... */ }因此,您的问题的答案非常简单:@ViewChildren和之间的区别@ContentChildren是,@ViewChildren在Shadow DOM 中查找元素,而@ContentChildren在Light DOM 中查找元素。

慕运维8079593

正如其名,@ContentChild并@ContentChildren查询将返回现有的内部指令<ng-content></ng-content>视图的元素,而@ViewChild并@ViewChildren不仅要看直接对你的视图模板元素。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

AngularJS