Angular 2.0 - @ViewQuery和@Query之间有什么区别

jak*_*ker 7 typescript angular

根据我在Angular 2文档中所读到的内容QueryList,@Query应该允许将子组件的引用注入给定组件.

使用@QueryView我设法获得对子DOM元素的引用,如下所示:

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

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

我希望@Query可以返回匹配的组件而不是DOM元素,但我还没有设法让它工作,也没有找到任何表明这样的文档.

这两个装饰器有什么区别?

ale*_*ods 12

首先,您必须了解Light DOM和Shadow DOM是什么.这些术语来自Web组件.所以这是链接.一般来说:

  • Light DOM -组件的最终用户提供给组件的DOM.
  • Shadow DOM - 是(作为组件创建者)定义并且对最终用户隐藏的组件的内部DOM.

我想,看下一个例子,你可以很容易地理解什么是什么(这里是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 { /* ... */ }
Run Code Online (Sandbox Code Playgroud)

所以,你的答案很简单:

之间的区别Query,并ViewQuery是,Query正在寻求在轻DOM元素,同时ViewQuery在阴影DOM寻找他们.

PS该示例显示简单的内容投影.但是<ng-content>可以做更复杂的事情.看到这个问题.

  • 不推荐使用`@ Query`和`@ViewQuery`,而是使用`@ ContentChildren`和`@ ViewChildren`. (3认同)
  • https://github.com/angular/angular/blob/master/modules/angular2/src/core/metadata.dart#L162,https://github.com/angular/angular/blob/master/modules/angular2/ SRC /核心/ metadata.dart#L137 (2认同)