Angular 2提供@ViewChild
,@ViewChildren
,@ContentChild
和@ContentChildren
用於查詢組件的後代元素的裝飾器。前兩者和後兩者有什麼區別?@ViewChild和@ContentChild有什麼區別?
回答
我會回答使用影子DOM和光DOM術語你的問題(它有來自網絡組件,請參閱here)。一般來說:
- 暗影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 { /* ... */ }
- 光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
尋找在陰影DOM元素,同時@ContentChildren
找他們光DOM。
來自Minko Gechew的博客文章http://blog.mgechev.com/2016/01/23/angular2-viewchildren-contentchildren-difference-viewproviders/對我來說更有意義。 @ContentChildren是通過內容投影插入的孩子(孩子介於
對我來說聽起來像' @ TemplateChildren'(而不是'@ ViewChildren')或'@ HostChildren'(而不是'@ ContentChildren')將會是更好的名字,因爲在這樣的上下文中,我們所談論的一切都是與視圖相關的,而且wrt綁定也是與內容相關的。 – superjos
'@ ViewChildren' ==你自己的孩子;'@ ContentChildren' ==別人的孩子 – candidJ
,顧名思義,@ContentChild
和@ContentChildren
查詢將返回現有的視圖的<ng-content></ng-content>
元素中的指令,而@ViewChild
和@ViewChildren
只看直接對你的視圖模板元素。
所以使用@ViewChild(ren),除非你在你的視圖中有組件,在這種情況下可以回到@ContentChild(ren)? –
這部影片從角連接有大約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返回單個實例時返回一個迭代。
- 1. 角2 - 不能與ViewChild也不ContentChild
- 2. 有什麼區別`和$(Bash中有什麼區別?
- 3. 有什麼區別? :和||
- 4. &&和||有什麼區別?
- 5. 「/」和「/ *」有什麼區別?
- 6. 有什麼區別:。!和:r!?
- 7. ==和===有什麼區別?
- 8. Appender和〜有什麼區別?
- 9. $ @和$ *有什麼區別?
- 10. is和=有什麼區別?
- 11. #.00和#。##有什麼區別?
- 12. `==`和`is`有什麼區別?
- 13. '=='和'==='有什麼區別?
- 14. /和/#/有什麼區別?
- 15. | 0和~~有什麼區別?
- 16. `&`和`ref`有什麼區別?
- 17. ==和===有什麼區別?
- 18. ==和===有什麼區別?
- 19. `{}`和`[]`有什麼區別?
- 20. JavaScript和=== ===有什麼區別?
- 21. difftime和' - '有什麼區別?
- 22. =和==有什麼區別?
- 23. xtype和別名有什麼區別?
- 24. Mixpanel:識別()和people.identify()有什麼區別?
- 25. 有什麼區別
- 26. 有什麼區別
- 27. 有什麼區別?
- 28. 有什麼區別?
- 29. 有什麼區別?
- 30. 有什麼區別
此鏈接幫助我http://blog.mgechev.com/2016/01/23/angular2-viewchildren-contentchildren-difference-viewproviders/閱讀下面的答案後。乾杯:) –