Skip to main content

Implementing Ionic Navigation

1. Setting Up Router Configuration

Property Description Default Notes
routes List of route configurations None Required for navigation setup
useHash Whether to use hash routing false Set to true for legacy browser support
enableHistoryApi Enable history API for navigation true Set to false to disable history API

Example: Basic Router Configuration

import { defineCustomElements } from '@ionic/core/loader';

defineCustomElements();

const router = document.querySelector('ion-router');
router.config([
  {
    path: '/home',
    component: 'app-home'
  },
  {
    path: '/profile',
    component: 'app-profile'
  }
]);
Note: The router configuration must be set up before any navigation occurs.

2. Navigating with Router

Property Description Values
routerLink Directive to navigate to a route /home, /user/123
routerLinkActive Applies CSS class to active route active
routerOutlet Directive to display routed components <ion-router-outlet>

Example: Basic Navigation

<ion-item routerLink="/home">
  <ion-label>Home</ion-label>
</ion-item>

<ion-router-outlet></ion-router-outlet>

Example: Navigation with Parameters

<ion-item routerLink="/user/123">
  <ion-label>User Profile</ion-label>
</ion-item>

// In component:
this.route.params.subscribe(params => {
  const userId = params['id'];
});

3. Passing Navigation Parameters

Parameter Type Description Usage Example
queryParams Query parameters passed as key-value pairs in the URL
this.router.navigate(['/page'], {
  queryParams: { id: '123', name: 'john' }
});
state Navigation state object passed to the target page (not in URL)
this.router.navigate(['/page'], {
  state: { data: 'someData' }
});

Example: Passing Parameters in Ionic Navigation

this.router.navigate(['/user-profile'], {
  queryParams: {
    userId: '12345',
    tab: 'profile'
  },
  state: {
    from: 'home'
  }
});
Note: Query parameters are visible in the URL and can be bookmarked, while state is not exposed in the URL.

4. Implementing Navigation Guards

Guard Type Description Implementation Use Case
CanActivate Controls if a route can be activated canActivate(): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree Authentication, authorization checks
CanDeactivate Controls if a route can be deactivated canDeactivate(component: any): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree Prompting user before navigation when changes exist
CanLoad Controls if a lazy-loaded module can be loaded canLoad(route: Route): Observable<boolean> | Promise<boolean> | boolean Restricting access to lazy-loaded modules

Example: CanActivate Guard

import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {
  constructor(private router: Router) {}

  canActivate(): boolean {
    const token = localStorage.getItem('authToken');
    if (token) {
      return true;
    } else {
      this.router.navigate(['/login']);
      return false;
    }
  }
}

Example: CanDeactivate Guard

import { Injectable } from '@angular/core';
import { CanDeactivate } from '@angular/router';

export interface CanComponentDeactivate {
  canDeactivate: () => Observable<boolean> | Promise<boolean> | boolean;
}

@Injectable({
  providedIn: 'root'
})
export class UnsavedChangesGuard implements CanDeactivate<CanComponentDeactivate> {
  canDeactivate(component: CanComponentDeactivate): boolean {
    if (component.canDeactivate()) {
      return true;
    } else {
      return confirm('You have unsaved changes. Are you sure you want to leave?');
    }
  }
}

5. Using Programmatic Navigation

Programmatic navigation in Ionic allows you to navigate between pages programmatically using the NavController or IonRouter (in Ionic 6+). This is useful for navigating based on user interactions, conditions, or asynchronous operations.

Method Description Usage Example
navigateForward() Navigates to a new page and adds it to the navigation stack.
import { NavController } from '@ionic/angular';

constructor(private navCtrl: NavController) {}

goToProfile() {
  this.navCtrl.navigateForward('/profile');
}
navigateBack() Navigates back to the previous page in the stack.
goBack() {
  this.navCtrl.navigateBack('/home');
}
navigateRoot() Navigates to the root page, clearing the navigation stack.
goToHome() {
  this.navCtrl.navigateRoot('/home');
}
setStack() Replaces the entire navigation stack with a new one.
setNewStack() {
  this.navCtrl.setStack(['/home', '/profile']);
}
Note: In Ionic 6+, IonRouter is preferred for more complex routing scenarios.

Example: Using IonRouter for Programmatic Navigation

import { IonRouter } from '@ionic/angular';

constructor(private ionRouter: IonRouter) {}

navigateToPage(pagePath: string) {
  this.ionRouter.navigateForward(pagePath);
}

6. Handling Back Button Navigation

Property Description Default
ionBackButton Component to customize the back button behavior in Ionic Default back button
backButtonDisabled Disables the back button in the header false
backButtonIcon Custom icon for the back button 'arrow-back'

Example: Custom Back Button

<ion-header>
  <ion-toolbar>
    <ion-buttons slot="start">
      <ion-back-button defaultHref="/home"></ion-back-button>
    </ion-buttons>
  </ion-toolbar>
</ion-header>

Example: Disable Back Button

<ion-header>
  <ion-toolbar>
    <ion-buttons slot="start">
      <ion-back-button backButtonDisabled="true"></ion-back-button>
    </ion-buttons>
  </ion-toolbar>
</ion-header>
Note: The defaultHref property sets the fallback route when the navigation stack is empty.
Warning: Disabling the back button can negatively impact user experience on mobile devices.

7. Configuring Page Transitions

Property Values Description
animated true | false Enables or disables page transition animations. Defaults to true.
duration number Duration of the transition animation in milliseconds. Defaults to 300.
easing string CSS easing function for the transition. Defaults to ease-in-out.
iosAnimated true | false Enables or disables animations specifically for iOS. Overrides animated.
mdAnimated true | false Enables or disables animations specifically for Material Design. Overrides animated.

Example: Setting Custom Transition Duration

import { NavController } from '@ionic/angular';

constructor(private navCtrl: NavController) {}

goToPage() {
  this.navCtrl.navigateForward('/page', {
    animated: true,
    duration: 500,
    easing: 'ease-in-out'
  });
}
Note: Transition properties can be set globally in IonicModule.forRoot({ ... }) or per navigation call.

8. Implementing Deep Linking

Deep linking in Ionic allows navigation to specific pages or states within an app using URLs. This feature enhances user experience by enabling direct access to content and improving SEO.

Feature Description Notes
Deep Linking Enables navigation to specific pages via URL paths Requires configuration in routing module
URL Structure Uses path segments to identify pages Example: /tabs/home
Router Configuration Configures URL patterns to component mappings Uses Angular's router or React Router

Example: Setting up Deep Linking in Ionic with Angular

import { NgModule } from '@angular/core';
import { PreloadAllModules, RouterModule, Routes } from '@angular/router';

const routes: Routes = [
  {
    path: 'home',
    loadChildren: () => import('./home/home.module').then(m => m.HomePageModule)
  },
  {
    path: 'tabs',
    loadChildren: () => import('./tabs/tabs.module').then(m => m.TabsPageModule)
  },
  {
    path: '',
    redirectTo: '/home',
    pathMatch: 'full'
  }
];

@NgModule({
  imports: [
    RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules })
  ],
  exports: [RouterModule]
})
export class AppRoutingModule { }
import { Component } from '@angular/core';

@Component({
  selector: 'app-tabs',
  template: `
    <ion-tabs>
      <ion-tab-bar slot="bottom">
        <ion-tab-button tab="home">
          <ion-icon name="home"></ion-icon>
          <ion-label>Home</ion-label>
        </ion-tab-button>
        <ion-tab-button tab="profile">
          <ion-icon name="person"></ion-icon>
          <ion-label>Profile</ion-label>
        </ion-tab-button>
      </ion-tab-bar>
    </ion-tabs>
  `
})
export class TabsPage {}
Note: Deep links require proper configuration in the app's routing module to ensure correct navigation and state management.

9. Using Navigation Lifecycle Hooks

Hook Description Usage
ionViewDidLoad Called once after the component is initialized and the view is attached to the DOM.
ionViewDidLoad() {
  console.log('Component loaded');
}
ionViewWillEnter Called every time the component is about to enter and become the active page.
ionViewWillEnter() {
  console.log('About to enter the page');
}
ionViewDidEnter Called every time the component has entered and become the active page.
ionViewDidEnter() {
  console.log('Page has entered');
}
ionViewWillLeave Called every time the component is about to leave and no longer be the active page.
ionViewWillLeave() {
  console.log('About to leave the page');
}
ionViewDidLeave Called every time the component has left and is no longer the active page.
ionViewDidLeave() {
  console.log('Page has left');
}
Note: These lifecycle hooks are specific to Ionic components and are not part of the standard Angular component lifecycle.

10. Managing Navigation Stack

Method Description Parameters Return Type
push() Navigates to a new page and adds it to the stack page: any, params?: any Promise<any>
pop() Removes the top page from the stack and navigates back options?: any Promise<any>
popTo() Pops pages until reaching a specific page page: any, options?: any Promise<any>
setRoot() Replaces the root page of the stack page: any, params?: any Promise<any>
getActive() Retrieves the currently active page none Page
getStack() Retrieves the current navigation stack none Page[]

Example: Pushing a new page

import { NavController } from 'ionic-angular';

constructor(public navCtrl: NavController) {}

goToProfile() {
  this.navCtrl.push('ProfilePage', { userId: 123 });
}

Example: Popping the current page

goBack() {
  this.navCtrl.pop();
}
Note: The navigation stack is managed by the Ionic framework and should not be manipulated directly.

Was this article helpful?