Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2.0 - What's the difference between @ViewQuery and @Query

From what I've read in the Angular 2 documentation of QueryList, @Query should allow for the ability to inject a reference to a child component into a given component.

Using @QueryView I've managed to get a reference to a child DOM element like so:

// Parent component's template
<my-component #test>

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

I expected that @Query may return the matching component rather than the DOM element, but I haven't managed to get it working, nor have I found any documentation that indicates so.

What's the difference between these two decorators?

like image 386
jaker Avatar asked Sep 20 '15 16:09

jaker


People also ask

What does !: Mean in Angular?

Means safe navigation operator. From Docs. The Angular safe navigation operator (?.) is a fluent and convenient way to guard against null and undefined values in property paths.

What is ViewChild in Angular?

A ViewChild is a component, directive, or element as a part of a template. If we want to access a child component, directive, DOM element inside the parent component, we use the decorator @ViewChild() in Angular.


1 Answers

First, you must understand what are the Light DOM and Shadow DOM. These terminologies have come from web components. So here is the link. In general:

  • Light DOM - is the DOM that the end-user of your component supply into your component.
  • Shadow DOM - is the internal DOM of your component that is defined by you (as a creator of the component) and hidden from the end-user.

I think, looking at the next example you can easily understand what is what (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 for you question is pretty simple:

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 The example shows simple content projection. But <ng-content> can do much more complex things. See this issue.

like image 55
alexpods Avatar answered Oct 09 '22 10:10

alexpods