Working with Ionic Lifecycle Hooks
1. Using ionViewWillEnter Hook
The ionViewWillEnter lifecycle hook is called every time a view is about to enter and become the active view. It's a key point in the Ionic lifecycle for performing setup or data fetching operations.
| Hook | Description | Usage |
|---|---|---|
| ionViewWillEnter | Called before the view enters and becomes active. | Use for data fetching, setting up event listeners, or initializing view-specific logic. |
Example: Using ionViewWillEnter in a Component
import { Component } from '@angular/core';<br><br>@Component({<br> selector: 'app-home',<br> templateUrl: 'home.page.html'<br>})<br>export class HomePage {<br> constructor() {}<br><br> ionViewWillEnter() {<br> console.log('Home page is about to enter');<br> // Fetch data or set up logic here<br> }<br>}
Note: Unlike
ionViewDidEnter, this hook is called before the view becomes active, so it's ideal for preparing data or setting up event listeners that should be ready before the view is displayed.
2. Using ionViewDidEnter Hook
| Property | Description | Usage |
|---|---|---|
| ionViewDidEnter | Called after the view has entered and is ready to be displayed | Use for initializing data or starting timers |
Example: ionViewDidEnter usage
import { Component } from '@angular/core';\n\n@Component({\n selector: 'app-home',\n templateUrl: 'home.page.html'\n})\nclass HomePage {\n ionViewDidEnter() {\n console.log('Home page is now visible');\n // Fetch data or start timers here\n }\n}
3. Using ionViewWillLeave Hook
The ionViewWillLeave lifecycle hook is called when the user is about to leave a page and navigate to another one. It's useful for cleaning up resources or saving data before the view is left.
| Hook Name | Description | Usage |
|---|---|---|
| ionViewWillLeave | Called when the user is about to leave a page and navigate to another one. | Use for cleanup or saving data before navigation. |
Example: Using ionViewWillLeave to save data
export class MyPage {
private userData: any = {};
ionViewWillLeave() {
// Save user data before leaving the page
this.saveUserData(this.userData);
}
private saveUserData(data: any) {
// Simulate saving data to a service or storage
console.log('Saving user data:', data);
}
}
Note: This hook is not called when the page is closed programmatically or when navigating using
ionBackButton.4. Using ionViewDidLeave Hook
The ionViewDidLeave lifecycle hook is called after a view has finished leaving and is no longer visible in the UI. It's useful for cleaning up resources or stopping operations that should not continue when the view is no longer active.
| Hook | Description | Use Case |
|---|---|---|
| ionViewDidLeave | Called after the view has left the screen and is no longer visible. | Cleaning up subscriptions, stopping timers, or unsubscribing from observables. |
Example: Using ionViewDidLeave to unsubscribe from a subscription
import { Component } from '@angular/core';
import { Subscription } from 'rxjs';
@Component({
selector: 'app-example',
templateUrl: './example.component.html'
})
export class ExampleComponent {
private subscription: Subscription;
ionViewDidEnter() {
this.subscription = this.dataService.getData().subscribe(data => {
console.log('Received data:', data);
});
}
ionViewDidLeave() {
if (this.subscription) {
this.subscription.unsubscribe();
console.log('Subscription unsubscribed');
}
}
}
Note: Unlike
ionViewWillLeave, ionViewDidLeave is called after the view has fully transitioned out of view, making it a good place to perform cleanup operations.
5. Understanding Lifecycle Order
| Hook | Description | Execution Order |
|---|---|---|
| ionViewDidLoad | Called once when the component is loaded | 1 |
| ionViewWillEnter | Called each time the component is about to enter and become active | 2 |
| ionViewDidEnter | Called each time the component has entered and become active | 3 |
| ionViewWillLeave | Called each time the component is about to leave and become inactive | 4 |
| ionViewDidLeave | Called each time the component has left and become inactive | 5 |
Example: Using Lifecycle Hooks in an Ionic Component
<ion-content>
<div class="content">
<h1>My Page</h1>
</div>
</ion-content>
Note: The lifecycle hooks are particularly useful for initializing data or setting up subscriptions when a page becomes active.
6. Using Component Lifecycle
Example: Basic Component Lifecycle Methods
import { Component, OnInit, OnDestroy } from '@angular/core';
@Component({
selector: 'app-example',
template: '<div>Example Component</div>'
})
export class ExampleComponent implements OnInit, OnDestroy {
ngOnInit() {
console.log('Component initialized');
}
ngOnDestroy() {
console.log('Component destroyed');
}
}
| Hook | Description | Usage |
|---|---|---|
| ngOnInit | Called after Angular has initialized the component | Initialize component logic here |
| ngOnChanges | Called when input properties change | React to property changes |
| ngOnDestroy | Called before Angular destroys the component | Clean up subscriptions and resources |
| ngAfterViewInit | Called after Angular has fully initialized the component's view | Access DOM elements or child components |
| ngAfterViewChecked | Called after Angular checks the component's view | Handle view changes (avoid heavy operations) |
| ngAfterContentInit | Called after Angular projects external content into the component | Access projected content |
| ngAfterContentChecked | Called after Angular checks the projected content | Handle content changes (avoid heavy operations) |
Note: Lifecycle hooks are specific to Angular and are used in Ionic components built with Angular.
7. Implementing Guards with Lifecycle
Example: Route Guard with Lifecycle
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { NavController } from '@ionic/angular';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(private navCtrl: NavController) {}
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): boolean {
const isLoggedIn = localStorage.getItem('isLoggedIn') === 'true';
if (!isLoggedIn) {
this.navCtrl.navigateRoot('/login');
return false;
}
return true;
}
}
| Guard Type | Description | Usage |
|---|---|---|
| CanActivate | Checks if a route can be activated | Used in routing to protect pages |
| CanDeactivate | Checks if a route can be deactivated | Used to prevent data loss on navigation |
| CanLoad | Checks if a module can be loaded lazily | Used for lazy loading modules |
Note: Guards are Angular features, not specific to Ionic, but they integrate well with Ionic's navigation system.
8. Handling Page Refresh
| Hook | Description | Usage |
|---|---|---|
| ionViewWillLoad | Called once when the page is about to load, before DOM rendering | Use for initial setup or data fetching before view renders |
| ionViewDidLoad | Called once after the page has loaded and DOM is ready | Use for DOM-related operations or initializing third-party libraries |
| ionViewWillEnter | Called every time the page is about to enter and become active | Use for operations that need to happen before each page visit (e.g., refresh data) |
| ionViewDidEnter | Called every time the page has entered and is active | Use for operations that should happen after each page visit (e.g., start timers) |
| ionViewWillLeave | Called every time the page is about to leave and become inactive | Use for cleanup or pausing operations before navigation |
| ionViewDidLeave | Called every time the page has left and become inactive | Use for final cleanup or logging after navigation |
Example: Refreshing Data on Page Enter
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
data: any[] = [];
ionViewWillEnter() {
this.refreshData();
}
refreshData() {
// Simulate API call
this.data = [{ id: 1, name: 'Item 1' }, { id: 2, name: 'Item 2' }];
}
}
Note:
ionViewWillEnter is ideal for refreshing data when the page becomes active, ensuring users always see the latest content.
9. Cleaning Up Resources
Example: Unsubscribing from Observables
import { Component, OnDestroy } from '@angular/core';
import { interval, Subscription } from 'rxjs';
@Component({
selector: 'app-example',
template: '<div>Timer: {{ count }}</div>'
})
export class ExampleComponent implements OnDestroy {
count = 0;
private subscription: Subscription;
constructor() {
this.subscription = interval(1000).subscribe(() => {
this.count++;
});
}
ngOnDestroy() {
if (this.subscription) {
this.subscription.unsubscribe();
}
}
}
| Resource Type | Cleanup Method | Notes |
|---|---|---|
| Event Listeners | removeEventListener() |
Manually remove listeners to prevent memory leaks |
| Intervals/Timers | clearInterval() or clearTimeout() |
Stop intervals to avoid continued execution |
| Subscriptions | unsubscribe() |
Unsubscribe from RxJS observables in ngOnDestroy |
| Native Plugins | plugin.destroy() |
Call destroy methods on Cordova plugins |
Note: Always clean up resources in
ngOnDestroy to prevent memory leaks and unexpected behavior.
10. Using Lifecycle with Navigation
| Hook | Description | Usage with Navigation |
|---|---|---|
| ionViewWillEnter | Called every time the page is about to enter and become the active page. | Use to refresh data or update UI when navigating back to a page. |
| ionViewDidEnter | Called after the page has fully entered and the transition is complete. | Use for initializing components or starting timers after navigation. |
| ionViewWillLeave | Called when the page is about to leave and no longer be the active page. | Use to clean up resources or pause operations before navigation. |
| ionViewDidLeave | Called after the page has fully left and is no longer active. | Use for final cleanup or logging after navigation. |
Note: These hooks are specific to Ionic's navigation stack and are not tied to Angular's lifecycle. They provide more granular control over page transitions.