I have 2 components, ComponentA & ComponentB, comp b is a child to comp a. ComponentB basically takes input from ComponentA & generates view. This input is obtained from a rest call. So I have wrapped my component b selector in an *ngIf. In this selector I also have a viewchild attached to it.
So basically, what I am assuming is that when ComponentB is completely rendered, I want to execute some code using my viewchild reference. This code is written in ngAfterViewInit() inside ComponentA. But when I try to access this.viewChildReference, it says undefined.
ComponentA.html
<div *ngIf="dataAvailable">
<componentb #viewChildReference [data]="dataFromComponentA"></componentb>
</div>
ComponentA.ts
// skipping boiler code for brevity
class {
dataAvailable = false;
@ViewChild('viewChildReference') viewChildReference: ChildComponentModule;
ngOnInit() {
// fetch data from rest
dataAvailable = true;
}
ngAfterViewInit() {
this.viewChildReference.somemethod();
}
}
ComponentB.html
// Use data from parent component and generate view
How can I solve this? What is wrong with my current approach? Please help as I am stuck up at this point..
UPDATE:
This question is not duplicate, as I have tried other solutions as suggested in comments in this question, like emitting events & other answers. Still I am facing issues, kindly unmark this as duplicate.