typescript – Angular 2.0 – @ViewQuery和@Query之间有什么区别

前端之家收集整理的这篇文章主要介绍了typescript – Angular 2.0 – @ViewQuery和@Query之间有什么区别前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
从我在QueryList的 Angular 2 documentation中读到的内容,@ Query应该允许将子组件的引用注入到给定组件中.

使用@QueryView我设法获得对子DOM元素的引用,如下所示:

  1. // Parent component's template
  2. <my-component #test>
  3.  
  4. // Parent component
  5. class ParentComponent {
  6. constructor(@Query('test') child: QueryList<any>) {...}
  7. }

我希望@Query可以返回匹配的组件而不是DOM元素,但是我没有设法让它工作,也没有找到任何表明这样的文档.

这两个装饰器有什么区别?

首先,您必须了解Light DOM和Shadow DOM是什么.这些术语来自Web组件.所以 here is the link.一般来说:

> Light DOM – 组件的最终用户提供给组件的DOM.
> Shadow DOM – 是您(作为组件的创建者)定义并且对最终用户隐藏的组件的内部DOM.

我想,看下一个例子,你可以很容易地理解什么是什么(here is the plunker):

  1. @Component({
  2. selector: 'some-component'
  3. })
  4. @View({
  5. template: `
  6. <h1>I am Shadow DOM!</h1>
  7. <h2>Nice to meet you :)</h2>
  8. <ng-content></ng-content>
  9. `;
  10. })
  11. class SomeComponent { /* ... */ }
  12.  
  13. @Component({
  14. selector: 'another-component'
  15. })
  16. @View({
  17. directives: [SomeComponent],template: `
  18. <some-component>
  19. <h1>Hi! I am Light DOM!</h1>
  20. <h2>So happy to see you!</h2>
  21. </some-component>
  22. `
  23. })
  24. class AnotherComponent { /* ... */ }

那么,你的答案很简单:

The difference between Query and ViewQuery is that Query is looking for elements in Light DOM while ViewQuery is looking for them in Shadow DOM.

PS该示例显示了简单的内容投影.但是< ng-content>可以做更复杂的事情.见this issue.

猜你在找的Angularjs相关文章