Ann*_*aya 16 viewchild angular
我是Angular2的新手.在我看来,我有几个相同的孩子在*ngFor中生成.
<ngb-panel *ngFor="let client of clients" [title]="'Client #' + client.id">
<template ngbPanelContent>
<processing-item [client]="client"></processing-item>
</template>
</ngb-panel>
Run Code Online (Sandbox Code Playgroud)
我需要在父元素中调用这些组件的方法并找出ViewChildren装饰器,代码是:
@ViewChildren(ProcessingItemComponent) processingItems: QueryList<ProcessingItemComponent>;
Run Code Online (Sandbox Code Playgroud)
然后我尝试通过forEach迭代它们:
ngAfterViewInit() {
this.processingItems.forEach(function (el) {
console.log(el);
});
}
Run Code Online (Sandbox Code Playgroud)
但它没有任何作用.在QueryList上调用的toArray()方法返回空数组.
任何建议如何一次获取所有子组件并调用其方法?
Gün*_*uer 21
如果clients是从异步调用(例如到服务器)设置,则元素尚不存在ngAfterViewInit().
您可以使用
ngAfterViewInit() {
this.processingItems.changes.subscribe(() => {
this.processingItems.toArray().forEach(el => {
console.log(el);
});
});
}
Run Code Online (Sandbox Code Playgroud)
另请参见https://angular.io/api/core/QueryList#changes