繁体   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