Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 390
Anna Ladyzhenskaya Avatar asked Aug 16 '17 09:08

Anna Ladyzhenskaya


People also ask

What is Querylist in Angular?

An unmodifiable list of items that Angular keeps up to date when the state of the application changes.

What is the difference between ViewChild () and ContentChild ()?

Any directive, component, and element which is part of component template is accessed as ViewChild. Whereas, any element or component which is projected inside <ng-content> is accessed as ContentChild.

What is @viewchildren in Angular?

What is @ViewChild in Angular? The @ViewChild decorator is used to query a single DOM element from the DOM tree and lets you manipulate it. To select an element from the template, three different parameters can be used. Selector : The selector of the element to query. It can be a directive type or a name.

How do you use View for kids?

In Angular, if we want to access the template information; i.e, any element from the html file in the ts file or in our component the we can choose the @viewchild concept. By using @viewchild we can achieve the following things, Accessing template of same component. Accessing the template of child component.


2 Answers

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

like image 195
Günter Zöchbauer Avatar answered Oct 16 '22 11:10

Günter Zöchbauer


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

@ContentChildren( OptionComponent ) public Options: QueryList<OptionComponent>; 
like image 22
Matthew Parton Avatar answered Oct 16 '22 12:10

Matthew Parton