How can I get children elements from QueryList in Angular 2?

故事扮演 提交于 2021-02-17 15:16:27

问题


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>

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>;

Then I try to iterate them by forEach:

ngAfterViewInit() {
    this.processingItems.forEach(function (el) {
        console.log(el);
    });
}

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?


回答1:


If clients is set from an async call (for example to the server) then the elements don't exist in ngAfterViewInit() yet.

You can use

ngAfterViewInit() {
  this.processingItems.changes.subscribe(() => {
    this.processingItems.toArray().forEach(el => {
        console.log(el);
    });
  });
}

See also https://angular.io/api/core/QueryList#changes




回答2:


I think you should be using the @ContentChildren attribute instead of the ViewChildren.

@ContentChildren( OptionComponent )
public Options: QueryList<OptionComponent>;


来源:https://stackoverflow.com/questions/45710194/how-can-i-get-children-elements-from-querylist-in-angular-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!