How can I get children from QueryList in Angular 2?

I am new to Angular2. In my opinion, I have several 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 the methods of these components in the parent element and find out the ViewChildren decorator, and the code:

 @ViewChildren(ProcessingItemComponent) processingItems: QueryList<ProcessingItemComponent>; 

Then I try to iterate them through Each:

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

But he does nothing. toArray (), called by QueryList, returns an empty array.

Any suggestions, how can I get all the child components in one go and call its methods?

+5
source share
1 answer

If clients are installed from an asynchronous call (for example, to a server), then the elements do not yet exist in ngAfterViewInit() .

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

+4
source

Source: https://habr.com/ru/post/1270914/


All Articles