2015-12-17 22 views
110

Angular 2提供@ViewChild,@ViewChildren,@ContentChild@ContentChildren用於查詢組件的後代元素的裝飾器。前兩者和後兩者有什麼區別?@ViewChild和@ContentChild有什麼區別?

+1

此鏈接幫助我http://blog.mgechev.com/2016/01/23/angular2-viewchildren-contentchildren-difference-viewproviders/閱讀下面的答案後。乾杯:) –

回答

164

我會回答使用影子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。

+3

來自Minko Gechew的博客文章http://blog.mgechev.com/2016/01/23/angular2-viewchildren-contentchildren-difference-viewproviders/對我來說更有意義。 @ContentChildren是通過內容投影插入的孩子(孩子介於之間)。來自Minkos博客:「另一方面,給定組件的主機元素的開始和結束標籤之間使用的**元素稱爲* content children **。「 Angular2中的Shadow DOM和視圖封裝在這裏描述:http://blog.thoughtram.io/angular/2015/06/29/shadow-dom-strategies-in-angular2.html。 – westor

+1

對我來說聽起來像' @ TemplateChildren'(而不是'@ ViewChildren')或'@ HostChildren'(而不是'@ ContentChildren')將會是更好的名字,因爲在這樣的上下文中,我們所談論的一切都是與視圖相關的,而且wrt綁定也是與內容相關的。 – superjos

+2

'@ ViewChildren' ==你自己的孩子;'@ ContentChildren' ==別人的孩子 – candidJ

65

,顧名思義,@ContentChild@ContentChildren查詢將返回現有的視圖的<ng-content></ng-content>元素中的指令,而@ViewChild@ViewChildren只看直接對你的視圖模板元素。

+0

所以使用@ViewChild(ren),除非你在你的視圖中有組件,在這種情況下可以回到@ContentChild(ren)? –

20

這部影片從角連接有大約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-aContentChildcomp-bViewChildCompomentChildrenViewChildren在xChild返回單個實例時返回一個迭代。