ionViewWillEnter and the problem
ionViewWillEnter is one of the Ionic Angular lifecycle events. There are instances where this lifecycle event will not fire due page transitions from tabs to a different page in separate ion-router-outlet components.
How does the problem occur?
When a user transitions from two different pages in an ionic app (ie from "/page1" to "/page2") these lifecycle events will fire such as ionViewWillLeave and ionViewDidLeave for /page1. Then with /page2 loading in the events ionViewWillEnter and then ionViewDidEnter will fire on the component for Page2. When staying within the same ion-router-outlet these events should fire the same way.
When a user navigates between various ion-router-outlet contexts, such as navigating from /tabs/tab1 to /page2, the tab the user was on remains the active tab but the tabs context transitions away. In this example, Tab1 remains the active tab but the context surrounding it is gone. The lifecycle events will fire on the root TabsPage component but not on Tab1.
The result is unexpected behavior where Tab1 has visually transitioned away but behind the scenes the whole context is gone too.
Workaround
If you wish to listen to lifecycle events on any individual tab page, there is an easy work around that can be implemented in your app to ensure these lifecycle events fire when expected.
tabs.page.html
<ion-tabs #tabs (ionTabsDidChange)="tabChange(tabs)">
...
</ion-tabs>
tabs.page.ts
import { Component } from '@angular/core'; import { IonTabs } from '@ionic/angular' @Component({ selector: 'app-tabs', templateUrl: 'tabs.page.html', styleUrls: ['tabs.page.scss'] }) export class TabsPage { private activeTab?: HTMLElement; constructor() {} tabChange(tabsRef: IonTabs) { this.activeTab = tabsRef.outlet.activatedView.element; } ionViewWillLeave() { this.propagateToActiveTab('ionViewWillLeave'); } ionViewDidLeave() { this.propagateToActiveTab('ionViewDidLeave'); } ionViewWillEnter() { this.propagateToActiveTab('ionViewWillEnter'); } ionViewDidEnter() { this.propagateToActiveTab('ionViewDidEnter'); } private propagateToActiveTab(eventName: string) { if (this.activeTab) { this.activeTab.dispatchEvent(new CustomEvent(eventName)); } } }
There are two things happening in this work around
- We keep track of the active tab element via ionTabsDidChange
- We listen for lifecycle events on the root tabs component and propagate them to the active tab (if one exists).
This explanation was sourced from a response to a GitHub issue.
Comments
0 comments
Please sign in to leave a comment.