Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 422
CyberRobot Avatar asked Apr 10 '17 08:04

CyberRobot


People also ask

What is viewchild in Angular 2?

The parent component was able to set the value of the child DOM Element. ViewChild makes it possible to access a child component and call methods or access instance variables that are available to the child. Let’s say we have a ChildComponent. Ideally, you will use @angular/cli to generate your component:

How to get the instance of the ngmodel in angular?

If we want to get the instance of the ngModel, then we use the Read token and ask for the type. Every element in Angular is always has a ElementRef and ViewContainerRef associated with it. If the element is a component or directive then there is always a component or directive instance. You can also apply more than one directive to an element.

Why does angular not render the child component immediately?

Because in the above case Angular does not render the child component immediately. But after the first change detection which detects the value of showCounter and renders the child component. Since we used static: true, the angular will try to resolve the ViewChild before the first change detection is run.

How to access the child variable in angular after view initialization?

The solution is to wait until the Angular Initializes the View. Angular raises the AfterViewInit life cycle hook once it completes the View Initialization. So we can use the ngAfterViewInit to access the child variable. Now, the code does not give any errors.


1 Answers

@ViewChildren(ChildComponent) childComponents: QueryList<ChildComponent>;
ngAfterViewInit(): void {
    this.networkService.connectSubscription(() => {
        this.childComponents.toArray();
    });
}
like image 168
Günter Zöchbauer Avatar answered Oct 21 '22 03:10

Günter Zöchbauer