@ViewChild 和 @ContentChild 有什么区别? [英] What's the difference between @ViewChild and @ContentChild?

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

问题描述

Angular 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?

推荐答案

我将使用 Shadow DOMLight DOM 术语(它来自网络组件,请参见此处).一般来说:

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

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

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

      所以,你的问题的答案很简单:

      So, the answer to your question is pretty simple:

      @ViewChildren@ContentChildren 的区别在于 @ViewChildren 在 Shadow DOM 中寻找元素,而 @ContentChildren 在 Light 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天全站免登陆