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?
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.
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.
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:
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
andViewQuery
is thatQuery
is looking for elements in Light DOM whileViewQuery
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With