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.
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:
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.
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.
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.
@ViewChildren(ChildComponent) childComponents: QueryList<ChildComponent>;
ngAfterViewInit(): void {
this.networkService.connectSubscription(() => {
this.childComponents.toArray();
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With