如何从 Angular 2 中的 QueryList 获取 children 元素?
How can I get children elements from QueryList in Angular 2?
我是 Angular2 的新手。在我看来,我几乎没有在 *ngFor.
中生成相同的 children
<ngb-panel *ngFor="let client of clients" [title]="'Client #' + client.id">
<template ngbPanelContent>
<processing-item [client]="client"></processing-item>
</template>
</ngb-panel>
我需要在parent元素调用这些组件的方法,找出ViewChildren装饰器,代码是:
@ViewChildren(ProcessingItemComponent) processingItems: QueryList<ProcessingItemComponent>;
然后我尝试通过 forEach 迭代它们:
ngAfterViewInit() {
this.processingItems.forEach(function (el) {
console.log(el);
});
}
但它什么也没做。在 QueryList returns 空数组上调用的 toArray() 方法。
关于如何一次获取所有 children 个组件并调用其方法的任何建议?
如果 clients
是从异步调用(例如对服务器)设置的,则元素在 ngAfterViewInit()
中尚不存在。
您可以使用
ngAfterViewInit() {
this.processingItems.changes.subscribe(() => {
this.processingItems.toArray().forEach(el => {
console.log(el);
});
});
}
我认为您应该使用@ContentChildren 属性而不是ViewChildren。
@ContentChildren( OptionComponent )
public Options: QueryList<OptionComponent>;
我是 Angular2 的新手。在我看来,我几乎没有在 *ngFor.
中生成相同的 children<ngb-panel *ngFor="let client of clients" [title]="'Client #' + client.id">
<template ngbPanelContent>
<processing-item [client]="client"></processing-item>
</template>
</ngb-panel>
我需要在parent元素调用这些组件的方法,找出ViewChildren装饰器,代码是:
@ViewChildren(ProcessingItemComponent) processingItems: QueryList<ProcessingItemComponent>;
然后我尝试通过 forEach 迭代它们:
ngAfterViewInit() {
this.processingItems.forEach(function (el) {
console.log(el);
});
}
但它什么也没做。在 QueryList returns 空数组上调用的 toArray() 方法。
关于如何一次获取所有 children 个组件并调用其方法的任何建议?
如果 clients
是从异步调用(例如对服务器)设置的,则元素在 ngAfterViewInit()
中尚不存在。
您可以使用
ngAfterViewInit() {
this.processingItems.changes.subscribe(() => {
this.processingItems.toArray().forEach(el => {
console.log(el);
});
});
}
我认为您应该使用@ContentChildren 属性而不是ViewChildren。
@ContentChildren( OptionComponent )
public Options: QueryList<OptionComponent>;