Search code examples
javascriptangularionic2angular2-components

Iterate through multiple @ViewChild instances of the same component angular2


I have an Ionic 2 application with a ParentComponent calling ChildComponent @ViewChild method to fire up multiple ChildComponents. One of the ChildComponents get's instantiated twice in the view with different parameters like so:

<ChildComponent [startFrom]="0" [limitTo]="1"></ChildComponent>
<ChildComponent [startFrom]="1" [limitTo]="1"></ChildComponent>

After an offline/online device state change, I call ChildComponent's method to update a list of items it returns.

@ViewChild(ChildComponent) childComponent: ChildComponent;

ngOnInit(): void {
    this.networkService.connectSubscription(() => {
        this.childComponent.getItems();
    });
}

The issue here is this.childComponent only get's hold of the first ChildComponent instance of the two.

Is there a way to iterate through multiple instances of the same @ViewChild component so I could do something like this.childComponent1.getItems() and this.childComponent2.getItems()?

Thanks for your help.


Solution

  • @ViewChildren(ChildComponent) childComponents: QueryList<ChildComponent>;
    
    ngAfterViewInit(): void {
        this.networkService.connectSubscription(() => {
            this.childComponents.toArray();
        });
    }