Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
987 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...