Lifecycle Events
Learn about Ionic and Angular lifecycle event hooks and incorporate them into the Ionic Navigation application.
We'll cover the following
Ionic lifecycle events
We can control what happens within our app before, during, and after pages have loaded with the following Ionic-specific navigation lifecycle events:
ionViewWillEnter
: event runs when the requested page is about to enter and become activeionViewDidEnter
: event runs when the page has completed entering and is now the active pageionViewWillLeave
: event runs when the page is about to leave and no longer be the active pageionViewDidLeave
: event runs when the previously active page has completed leaving
Since Ionic 4 and the closer integration with the underlying Angular framework, it is recommended that the Angular lifecycle hooks are used instead where possible as, unfortunately, there are no like-for-like equivalents for each of the available Ionic/Angular lifecycle hooks.
Angular lifecycle hooks
These are as follows:
- The
ngAfterContentChecked
hook is triggered after Angular checks the content that has been projected into the component or directive - The
ngAfterContentInit
hook is triggered after Angular projects content into a component view or the view that a directive is loaded into - The
ngAfterViewChecked
hook is triggered after Angular checks the component view/view into which a directive is loaded - The
ngAfterViewInit
hook is triggered after Angular initializes the component’s views and child views - The
ngDoCheck
hook detects and acts on changes that Angular can’t or won’t detect. - The
ngOnChanges
hook is triggered when Angular sets and resets data-bound input properties - The
ngOnDestroy
hook is triggered just before Angular destroys the component or directive and performs cleanup tasks such as detaching event handlers and unsubscribing Observables - The
ngOnInit
hook is triggered once after Angular first displays data-bound properties and sets directive or component input properties
Using lifecycle events
Let’s see how both the Ionic and Angular lifecycle event hooks can be used within the Ionic Navigation project we’ve been building so far.
In the ionic-navigation/src/app/pages/details-page/details.page.ts
file, we add the following logic for the lifecycle event hooks (added code is highlighted):
Get hands-on with 1200+ tech skills courses.