Lifecycle hooks for inner components

Hi,
I am learning Ionic 2 now and I finding it hard to find out how to solve this issue.

I have a page that every time a user enter, it gets and updates data from the server using ionViewWillEnter hook. I want to separate this feature on a new component to be used in other pages.

This new component will be used by inserting his element tag on the pages. The problem is that ionViewWillEnter (neither other hooks) is not called in this component. It seems to be called only in Page Components. I change the code to use Angular 2 hook ngOnInit and the component works fine, but this hook is not called again when user navigates between pages.

Is there any way to refresh this component by calling a specific method whenever ionViewWillEnter was called on the PageComponent.

Thanks.

7 Likes

Hi,

I have a similar issue.
I want to get rid of listeners I set inside my component.
If it would be a page I could just use ionViewWillLeave but unfortunately these methods do not get triggered inside components.

I got close to what I want to achieve by listening to the events on the navController like that:

this.nav.viewDidLeave.first().subscribe(() => {
 // .. do stuff ..
});

But these “leave-events” get triggered for leaving the last page too. So it kills my listeners (which are set inside ngOnInit) right after they are set.

Any ideas how to get a one-time hook fore leaving views inside a component?

I am running into same problem here where in my custom component I need functionality of ionViewWillEnter() and ionViewWillLeave(). Angular2 lifecycle hooks dont really provide that.

Wondering how did you guys solve this?

One hack I can think of is to change my component to a IonicPage. As far as I see, there isnt much difference between the two. Any downside to this?

Hi!
An inner component knows nothing about Ionic lifecycle events. Ionic/pages will not notify inner components about loading, become the active page, etc. If you need your inner component to do something based on lifecycle events, tie the parent lifecycle event with the inner component using Angular’s @ViewChild decorator.

In parent component get a reference to the child component using @ViewChild as explained here. Then, inside the parent lifecycle event, call a public function defined in child component.

Hope it helps,
Xavi

7 Likes

Please describe how can tie the parent lifecycle event with the inner component using Angular’s @ViewChild decorator.