user3847870
user3847870

Reputation: 410

ngAfterViewInit of Parent Vs ngAfterViewInit of child

Will ngAfterViewInit of Parent always run after the ngAfterViewInit of child ?

<Parent>
 <child></child>
<Parent>

From parent's ngAfterViewInit I am emitting some data to child . In Child's ngAfterViewInit I am subscribing to the the data. But the subscription is not triggered. Child in my case is a grid which has heavy api calls in ngOnInit. When I consoled logged I found out Child's ngAfterViewInit is running after the parent's ngAfterViewInit. So when I emit payload from Parent's ngAfterViewInit the subscribers in Child are not configured as its ngAfterViewInit ran after I emitted the payload from the parent.

Upvotes: 3

Views: 2165

Answers (1)

Yes, ngAfterViewInit of the parent component will always run after the child.

In the angular docs that you can find here about ngAfterViewInit is said that :

Respond after Angular initializes the component's views and child views, or the view that contains the directive.

So if we trust the docs the first ngAfterViewInit will be always called from the "most-nested" visible component part of the view.

If you don't trust the docs :D here is a stackblitz open the console and observe.

About passing data between components, you can always pass the data trough the @Input and things will most likely work.

Edit

I saw the additional info in your comment, another way in which you can interact with your child component from the parent is by using @ViewChild, if you target the child component with @ViewChild you can invoke whatever method you need from the child inside the parent's ngAfterViewInit

Upvotes: 5

Related Questions