什么是@ViewChild和@ContentChild之间的区别? [英] What's the difference between @ViewChild and @ContentChild?

查看:983
本文介绍了什么是@ViewChild和@ContentChild之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

2角提供 @ViewChild @ViewChildren @ContentChild 和查询组件的后代元素 @ContentChildren 装饰。什么是前两者和后两者之间的区别?

Angular 2 provides @ViewChild, @ViewChildren, @ContentChild and @ContentChildren decorators for querying a component's descendant elements. What's the difference between the first two and the latter two?

推荐答案

我将使用回答你的问题的阴影DOM 光DOM 术语(它有来自网页组件,请参阅这里)。一般来说:

I'll answer your question using Shadow DOM and Light DOM terminology (it have come from web components, see here). In general:


  • 阴影DOM - 为您的组件的内部DOM被定义的由您(作为组件的创< /强>)和从最终用户隐藏。例如:

  • Shadow DOM - is an internal DOM of your component that is defined by you (as a creator of the component) and hidden from an end-user. For example:
@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。例如:

    • Light DOM - is a DOM that an end-user of your component supply into your component. For example:
    • @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 { /* ... */ }
      

      所以,回答你的问题是pretty简单:

      So, the answer to your question is pretty simple:

      @ViewChildren @ContentChildren @ViewChildren 寻找在影子DOM元素,而 @ContentChildren 寻找他们光在DOM。

      The difference between @ViewChildren and @ContentChildren is that @ViewChildren look for elements in Shadow DOM while @ContentChildren look for them in Light DOM.

      这篇关于什么是@ViewChild和@ContentChild之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆