Angular 2.0 - What is the difference between @ViewQuery and @Query

From what I read in the Angular 2 QueryList documentation , @Query should consider the possibility of injecting a reference to a child component in this component.

Using @QueryView I was able to get a link to a child DOM element, for example:

 // Parent component template <my-component #test> // Parent component class ParentComponent { constructor(@Query('test') child: QueryList<any>) {...} } 

I was expecting @Query to return the corresponding component, not the DOM element, but I was not able to get it to work, and I did not find the documentation that indicates this.

What is the difference between these two decorators?

+7
angular typescript
source share
1 answer

First, you need to understand what the DOM DOM and Shadow DOM are. These terminologies are taken from web components. So here is the link . Generally:

  • Light DOM is the DOM that the end user of your component ships with in your component.
  • The DOM shadow is the internal DOM of your component, which is used by you (as the creator of the component ) and hidden from the end user.

I think looking at the following example, you can easily understand what is ( here is the plunker ):

 @Component({ selector: 'some-component' }) @View({ template: ` <h1>I am Shadow DOM!</h1> <h2>Nice to meet you :)</h2> <ng-content></ng-content> `; }) class SomeComponent { /* ... */ } @Component({ selector: 'another-component' }) @View({ 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 quite simple:

The difference between Query and ViewQuery is that Query looks for elements in the Light DOM, and ViewQuery looks for them in the Shadow DOM.

PS The example shows a simple projection of the content. But <ng-content> can do much more complex things. See this question .

+12
source share

All Articles