如何从Angular 2的QueryList中获取子元素? [英] How can I get children elements from QueryList in Angular 2?
问题描述
我是Angular2的新手.在我看来,我在* ngFor中生成的几个相同的子代.
I am newbie at Angular2. In my view I have few identical children that are generated in *ngFor.
<ngb-panel *ngFor="let client of clients" [title]="'Client #' + client.id">
<template ngbPanelContent>
<processing-item [client]="client"></processing-item>
</template>
</ngb-panel>
我需要在父元素处调用这些组件的方法,并找出ViewChildren装饰器,其代码为:
I need to call methods of these components at parent element and find out the ViewChildren decorator and the code is:
@ViewChildren(ProcessingItemComponent) processingItems: QueryList<ProcessingItemComponent>;
然后我尝试通过forEach对其进行迭代:
Then I try to iterate them by forEach:
ngAfterViewInit() {
this.processingItems.forEach(function (el) {
console.log(el);
});
}
但是它什么也没做.QueryList上调用的toArray()方法返回空数组.
But it does nothing. toArray() method called on QueryList returns empty array.
任何建议如何一次获得所有子组件并调用其方法?
Any suggestions how can I get all children components at one time and call its methods?
推荐答案
如果通过异步调用(例如服务器)设置了 clients
,则元素在 ngAfterViewInit()
中尚不存在.
If clients
is set from an async call (for example to the server) then the elements don't exist in ngAfterViewInit()
yet.
您可以使用
ngAfterViewInit() {
this.processingItems.changes.subscribe(() => {
this.processingItems.toArray().forEach(el => {
console.log(el);
});
});
}
另请参见 https://angular.io/api/core/QueryList#changes
这篇关于如何从Angular 2的QueryList中获取子元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!