簡體   English   中英

@ViewChild 和 @ContentChild 有什么區別?

[英]What's the difference between @ViewChild and @ContentChild?

Angular 2 提供了@ViewChild@ViewChildren@ContentChild@ContentChildren裝飾器,用於查詢組件的后代元素。

前兩者和后兩者有什么區別?

我將使用Shadow DOMLight DOM術語回答您的問題(它來自 Web 組件,請在此處查看更多信息)。 一般來說:

  • 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 { /* ... */ }

所以,你的問題的答案很簡單:

之間的區別@ViewChildren@ContentChildren@ViewChildren尋找在陰影DOM元素,同時@ContentChildren尋找他們光在DOM。

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

來自 Angular Connect 的這段視頻提供了關於 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-bViewChild CompomentChildrenViewChildren返回一個可迭代對象,而 xChild 返回單個實例。

讓我們舉個例子,我們有一個主組件和一個子組件,內部子組件有一個小子組件。

<home>
     <child>
           <small-child><small-child>
     </child>
</home>

現在您可以使用@viewChildren 獲取 home 組件上下文中的所有子元素,因為它們是直接添加到 home 組件的模板中的。 但是,當您嘗試從子組件的上下文訪問<small-child>元素時,您將無法訪問它,因為它沒有直接添加到子組件模板中。 它是通過內容投影由主組件添加到子組件中的。 這是@contentChild 的用武之地,您可以使用@contentChild 來獲取它。

當您嘗試訪問控制器中的元素引用時會出現差異。 您可以訪問通過@viewChild 直接添加到組件模板中的所有元素。 但是您無法使用@viewChild 獲取投影元素引用要訪問投影元素,您必須使用@contentChild。

只需將 ViewChildren 重命名為 InternalChildren,將 ContentChildren 重命名為 ExternalChildren

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM