我想从模板中定义的组件获取引用。让我们考虑一下我有以下组件:
@Component({
selector: 'a-component'
})
@View({
template: '<another-component #anotherComponent></another-component>',
directives: [AnotherComponent]
})
class AComponent {
callAnotherComponent() {
anotherComponent.doSomething();
}
}
显然这不起作用,我的类中的 anotherComponent 未定义。但有什么简单的方法可以做到这一点吗?在我的例子中, AnotherComponent 应该是一个弹出组件,我想简单地调用类似 myPopupCmp.showMessage("message") 的东西。
我当然可以使用数据绑定(bind)并在我的模板中像这样使用它:<another-component [text]="popupText" [visible]="isPopupVisible"></another-component>
,并使用这两个成员通过首先设置文本然后使其可见来显示它。在大多数情况下,数据绑定(bind)是有意义的,但在这里我想封装属性并避免必须在使用弹出窗口时处理弹出窗口的行为。
编辑:
@EricMartinez 经过一番研究,我更新了你的 plnkr,这里是 fork 的链接:plnkr 。技巧是使用@ViewQuery,它用于查询组件 View 中的指令和dom元素。我在这个问题中发现了这一点:angular2 github 。
现在的问题是 _results 似乎是空的,尽管如果我在控制台中展开 View ,我可以看到我的组件,而且我什至可以看到它的属性,所以数据以某种方式存在,但我无法访问它。是否有使用 QueryLists 的特殊方法?使用 _results 看起来不太干净,因为 _ 表明它应该是私有(private)的或内部的。我也尝试使用first,但它总是带来空引用。
最佳答案
截至https://github.com/angular/angular/commit/b0e2ebda708cf25287a211a30ef63d84cdb92a7f你应该能够做到:
class AComponent {
constructor(@Query('#anotherComponent') query:QueryList<AnotherComponent>) {
}
}
关于angular - 获取对模板中组件的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31905907/