This article is part of the Ionic Framework / Capacitor Advent Calendar 2020.
Among the reasons an Ionic/Angular feature "just does not work," a common one is a typo in a lifecycle method name. Ionic defines its own lifecycle events to support push and pop navigation:
| Event Name | Description |
|---|---|
| ionViewWillEnter | Fires when the animation to show the component starts. |
| ionViewDidEnter | Fires when the animation to show the component finishes. |
| ionViewWillLeave | Fires when the animation to leave the component starts. |
| ionViewDidLeave | Fires when the animation to leave the component finishes. |
Like ngOnInit and ngOnDestroy, you place methods with these exact names on the page component and they fire. Because the names must match exactly, writing IonViewWillEnter() (capital I) will not fire—and it can look fine at a glance, so the cause is hard to spot.
To prevent that, Ionic/Angular provides interfaces you can implements on the class. Just as you implements OnInit in Angular, implements the lifecycle interfaces you use.
import { ViewDidEnter, ViewWillEnter, ViewDidLeave, ViewWillLeave } from '@ionic/angular';
@Component({
selector: 'app-home',
templateUrl: './home.page.html',
styleUrls: ['./home.page.scss'],
})
export class HomePage implements ViewDidEnter, ViewWillEnter, ViewWillLeave, ViewDidLeave {
ionViewDidEnter() {}
ionViewWillEnter() {}
ionViewWillLeave() {}
ionViewDidLeave() {}
(You do not need to implements all of them as shown—add only what you need.)
That alone makes the class aware those methods are required, so the compiler warns if you forget one or typo the name.
Eliminate typos and enjoy a better dev life!
See you next time.