Angular 2.0 - @ViewQuery 和 @Query 有什么区别
Angular 2.0 - What's the difference between @ViewQuery and @Query
根据我在 QueryList
的 Angular 2 documentation 中所读到的内容,@Query
应该允许将对子组件的引用注入给定组件的能力。
使用 @QueryView
我设法获得了对子 DOM 元素的引用,如下所示:
// Parent component's template
<my-component #test>
// Parent component
class ParentComponent {
constructor(@Query('test') child: QueryList<any>) {...}
}
我预计 @Query
可能 return 匹配组件而不是 DOM 元素,但我没有设法让它工作,也没有找到任何文档表示如此。
这两个装饰器有什么区别?
首先,你必须了解什么是光DOM和影DOM。这些术语来自网络组件。所以here is the link。总的来说:
- Light DOM - 是 的最终用户 DOM您的组件 供应给您的组件。
- Shadow DOM - 是组件的内部 DOM 定义的 由您(作为组件创建者)编写,对最终用户隐藏。
我想,看下一个例子你可以很容易地理解什么是什么(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 { /* ... */ }
所以,你问题的答案很简单:
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。
根据我在 QueryList
的 Angular 2 documentation 中所读到的内容,@Query
应该允许将对子组件的引用注入给定组件的能力。
使用 @QueryView
我设法获得了对子 DOM 元素的引用,如下所示:
// Parent component's template
<my-component #test>
// Parent component
class ParentComponent {
constructor(@Query('test') child: QueryList<any>) {...}
}
我预计 @Query
可能 return 匹配组件而不是 DOM 元素,但我没有设法让它工作,也没有找到任何文档表示如此。
这两个装饰器有什么区别?
首先,你必须了解什么是光DOM和影DOM。这些术语来自网络组件。所以here is the link。总的来说:
- Light DOM - 是 的最终用户 DOM您的组件 供应给您的组件。
- Shadow DOM - 是组件的内部 DOM 定义的 由您(作为组件创建者)编写,对最终用户隐藏。
我想,看下一个例子你可以很容易地理解什么是什么(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 { /* ... */ }
所以,你问题的答案很简单:
The difference between
Query
andViewQuery
is thatQuery
is looking for elements in Light DOM whileViewQuery
is looking for them in Shadow DOM.
PS 该示例显示了简单的内容投影。但是 <ng-content>
可以做更复杂的事情。参见 this issue。