Detect children finish loaded using @ViewChild and *ngIf

I need to execute a children component code only one-time, from the father in ngAfterViewInit() method

When I use @ViewChild this return undefined for the time it takes to load certain http requests.
I want to avoid using setTimeout since I do not know how long it can take http requests

using @ViewChildren I get to know when the child component is not null
but my code is executed multiple times

this.childPage.changes.subscribe((comps: QueryList) =>
// Now you can access to the child component
if(this.childPage.last != null){
// I execute my code here

same problem using a setter for @ViewChild()

@ViewChild(ChildPage) set childPage(childPage: ChildPage) {
if(childPage!= null){
// I execute my code here

Any idea how to achieve this?

This sounds like an extremely brittle design. The point of separating things into components is so they can be completely independent of their surroundings, communicating only through well-defined interfaces like @Input and @Output properties. I would suggest thinking of a way to make this problem go away by not having the need in the first place.

But the code that I have to execute is particular to the child component.

If I have to pass it as input then I should replicate the code in each of the parents that contain the child

I don’t understand what you are saying, but why can’t the child component be self-sufficient? Why can’t it have all the code needed for it inside it, without any parental involvement?

I need to populate a combo that is inside the child. The combo is filled from an HTTP request which should be called when the view (parent) is displayed.

I think you have two choices:

  • fire the HTTP request from the child, passing whatever information is needed to make it via an @Input property
  • fire the HTTP request from the parent and pass the results into the child via an @Input property

Personally, I would default to the second option, because it makes the child more reusable - it could do its job even if the data is coming from some other source than this HTTP request. The only downside is that you have to duplicate the code to create the food for the client in the various parents, but I would actually view that as an opportunity. All the data wrangling should be in a service provider, in which case the code in the parents can be just one line.

thanks! work for me!