我正在尝试使用@Query
来获取有关模板中元素的一些信息。但我似乎无法让它发挥作用。
我试过这样做:Documented here Mine看起来像这样,
import {Component, Query, QueryList, ElementRef} from 'angular2/core';
@Component({
selector : 'my-app',
template : `
<banner #banner>
<h4>Some New App</h4>
</banner>
<div class="container"></div>
`
})
export class App
{
private banner:any;
constructor(@Query('banner') banner:QueryList<ElementRef>)
{
this.banner = banner;
}
ngOnInit()
{
console.log(this.banner)
}
}
控制台日志显示如下:
现在我在这里错了。但我希望_results: Array[0]
有一个结果。我希望它包含有关<h4>
元素的一些信息。
所以考虑到这一点。我尝试按照文档后的几种不同方式进行操作。我见过一些人使用kabob案件,有些人使用骆驼等。所以我想也许文档还没有更新。
经过更多的搜索,我遇到了这个https://github.com/angular/angular/issues/3922
@Query
已更改为此语法吗?
@ContentChild()
和@ViewChildren()
无论哪种方式,我的问题是今天做到这一点的正确方法是什么?或者我在这里完全遗漏了什么?
@Query
相当于@ContentChild/@ContentChildren
(通过ng-content
投影的元素),因此它无法查询视图中的元素。你想要的是@ViewQuery()
。也就是说,你最好不要使用@Query
和@ViewQuery
,因为这个API will be removed。
这是您的代码更正
import {Component, ViewChildren, QueryList, ElementRef} from 'angular2/core';
@Component({
selector : 'my-app',
template : `
<banner #banner>
<h4>Some New App</h4>
</banner>
<div class="container"></div>
`
})
export class App {
@ViewChildren('banner') banner: QueryList<ElementRef>;
ngAfterViewInit() {
console.log(this.banner)
}
}
这是一个plnkr,您的示例使用当前的API。