Shaul Naim
Shaul Naim

Reputation: 276

Angular (2+) : how can i know from parent component when all child-components were initialized?

is there a lifecycle hook so-called "ngAfterAllChildrenInit" because ngAfterViewInit is called before ngOninit of the children,

I am trying to avoid hacking with setTimeOut or emitting events from all the children and collecting them and then do what I want ( that depend on the children initialization)

it seems so common why is it not part of angular?

Upvotes: 2

Views: 3663

Answers (3)

tigerpaw
tigerpaw

Reputation: 145

how about use a service. the last child publish an event through observable, and the parent subscribes to it.

Upvotes: 0

Mehdi Benmoha
Mehdi Benmoha

Reputation: 3945

Angular Lifecycle hooks are very powerful, in order to achieve what you want, you can simply use the OnInit lifecycle hook. Angular is reading your template file and running your component in a vertical way (from top to down). So, you just have to do whatever you want in your last component's ngOnInit method.

If your components are used in different parts of your application, you can check that the parent component is the one you want by using the @Host decorator (see the answer of @trichetriche).

I created a stack blitz where there's 3 components used in the app component (parent) in this order:

<hello name="{{ name }}"></hello>
<app-child></app-child>

So the AppComponent OnInit hook will fire first, and after that the HelloComponent OnInit and finally the ChildComponent.

See it in action on the console: https://stackblitz.com/edit/angular-62xjux

EDIT: You can use the ngAfterViewChecked as the documentation specifies:

Respond after Angular checks the component's views and child views / the view that a directive is in.

Called after the ngAfterViewInit and every subsequent ngAfterContentChecked().

Upvotes: 0

user4676340
user4676340

Reputation:

You could use decorators for that. I mean, Angular decorators, not custom ones.

In your parent :

activated: any = {};

In your children :

constructor(@Host() parent: ParentComponent) {}

// Hook of your choice
ngOnInit() { this.parent.activated[this.constructor.name] = true; }

This will create an activated object like this

activated = {
  FirstChildComponent: true
  // Second not initialized ? Then not here and activated[SecondChildComponent] = undefined
};

Upvotes: 1

Related Questions