简体   繁体   English

如何获取Angular2模板中特定组件的引用?

[英]How to get a reference to a particular component in an Angular2 template?

I know that Angular2 has @ViewQuery to get a QueryList of components matching the given type. 我知道Angular2有@ViewQuery来获取与给定类型匹配的组件的QueryList But is there a way to get a reference to a particular component in this QueryList ? 但有没有办法获得对此QueryList的特定组件的QueryList

Right now, the only way I can think to do this is to give the component an extra "id" field, then iterate through the QueryList and check if the identifier is the one I want, eg: 现在,我能想到的唯一方法就是给组件一个额外的“id”字段,然后遍历QueryList并检查标识符是否是我想要的,例如:

getComponentById(QueryList<HasIdField> queryList, String id) =>
    queryList.singleWhere((component) => component.id == id);

But this seems like a common enough problem that it seems like there should be a way to do this without adding this "id" boilerplate. 但这似乎是一个常见的问题,似乎应该有一种方法来做到这一点,而不添加这个“id”样板。 I know that a component can be referenced locally within a template using # , but is there a way to reference a component similarly within a class? 我知道可以使用#在模板中本地引用组件,但是有没有办法在类中类似地引用组件?

Currently this functionality does not exist, see here for details on why the functionality to implement a custom filter is currently on hold due to potential performance reasons. 目前此功能不存在,请参阅此处 ,详细了解由于潜在的性能原因,实现自定义过滤器的功能目前暂停的原因。

So the way you are doing it seems to be the right way given the functionality that is available currently, but this might change as the framework is now in alpha. 因此,考虑到当前可用的功能,您正在采用的方式似乎是正确的方式,但这可能会随着框架现在处于alpha状态而发生变化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM