Ionic 4/Angular 7 lifecycle hooks called just one time per page

Natanael picture Natanael · Dec 29, 2018 · Viewed 6.9k times · Source

In ionic 3 there was lifecycle events like ionViewWillEnter and ionViewWillLeave. But in Ionic 4 this event must be replaced by Angular lifecycle events like ngOnInit and ngOnDestroy.

In my application I need to realize some given operations when the user enter or leaves a page. For example, if the user push another page (navigate forward in Ionic 4), the app whould execute ionViewWillLeave for the current page before the new page being pushed. If the user came back from a pushed page (navigate backward in Ionic 4) the app whould execute ionViewWillEnter for the previous page.

I tried to replace this events with ngOnInit and ngOnDestroy. But this events are called just one time each per page. For example, if I route to another page (navigate root in Ionic 4) and came back to the first page, the first page the ngOnInit and ngOnDestroy events will not be called again.

How can I call a event each time a user enter or leaves a page?

Answer

Natanael picture Natanael · Dec 29, 2018

I made a mistake. The documentation says:

With V4, we're now able to utilize the typical events provided by Angular. But for certain cases, you might want to have access to the events fired when a component has finished animating during it's route change. In this case, the ionViewWillEnter, ionViewDidEnter, ionViewWillLeave, and ionViewDidLeave have been ported over from V3. Use these events to coordinate actions with Ionic's own animations system.

Older events like ionViewDidLoad, ionViewCanLeave, and ionViewCanEnter have been removed, and the proper Angular alternatives should be used. Migration Guide - Lifecycle Events