Navigation and Routing

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

Navigation in an Ionic app feels like navigation in a native app: pages slide in on a stack, going back reverses the animation, tabs keep their own history, and the Android back button behaves as users expect. Ionic does not replace the router of the framework it runs on. It adds ion-router-outlet, which renders routed pages inside a navigation stack and animates the transitions, and it keeps pages alive while they are in the stack. This page uses the Angular Router; the concepts carry over to React and Vue. The Trailhead hiking journal serves as the example, building on the pages from Components and Theming. For the router itself, see the Angular routing reference.

The Trailhead Route Structure

Trailhead has a tab bar with two tabs, trails and favourites. The trail detail and the log-a-hike page are pushed on top of the trails tab.

flowchart TB root["ion-app with ion-router-outlet"] tabs["tabs page: ion-tabs and ion-tab-bar"] trails["trails tab: TrailListPage"] favs["favourites tab: FavouritesPage"] detail["trails/:id: TrailDetailPage"] log["trails/:id/log: LogHikePage"] root --> tabs tabs --> trails tabs --> favs trails -->|push| detail detail -->|push| log log -.->|back| detail detail -.->|back| trails

Routes and ion-router-outlet

The application root contains a single ion-router-outlet. Routes are plain Angular route objects, and standalone components are loaded lazily with loadComponent, so each page becomes its own chunk:

// src/app/app.routes.ts
import { Routes } from '@angular/router';
import { authGuard } from './auth/auth.guard';

export const routes: Routes = [
  {
    path: '',
    loadComponent: () => import('./tabs/tabs.page').then((m) => m.TabsPage),
    children: [
      {
        path: 'trails',
        loadComponent: () => import('./trails/trail-list.page').then((m) => m.TrailListPage),
      },
      {
        path: 'favourites',
        loadComponent: () => import('./favourites/favourites.page').then((m) => m.FavouritesPage),
      },
      { path: '', redirectTo: 'trails', pathMatch: 'full' },
    ],
  },
  {
    path: 'trails/:id',
    loadComponent: () => import('./trails/trail-detail.page').then((m) => m.TrailDetailPage),
  },
  {
    path: 'trails/:id/log',
    canActivate: [authGuard],
    loadComponent: () => import('./log-hike/log-hike.page').then((m) => m.LogHikePage),
  },
];

The root component’s template is just <ion-app><ion-router-outlet></ion-router-outlet></ion-app>; the full component appears in the deep link section below.

Route parameters can be bound to component inputs by adding withComponentInputBinding() to provideRouter, which is how TrailDetailPage reads its id input. Preloading is configured with provideRouter(routes, withPreloading(PreloadAllModules)): all lazy chunks are fetched in the background after the first page, which matters on a device because the files are local and cheap to load.

Stack Navigation and Transitions

ion-router-outlet implements a stack. Navigating forward pushes a new page on top and animates it in; the page below stays in the DOM, with its state intact. Navigating back pops the top page and destroys it. This is the main difference from a web router, which usually destroys the previous page.

Navigation can be triggered in several ways:

  • A routerLink on an element or on an ion-item, as in the trail list. Ionic adds the routerDirection attribute to hint the animation: forward, back or root.

  • Router.navigate, or Ionic’s NavController, which adds explicit direction control.

  • ion-back-button, which pops the stack, or goes to defaultHref when there is no history (for example after a deep link).

import { Component, inject } from '@angular/core';
import { NavController } from '@ionic/angular/standalone';

@Component({ selector: 'app-example', template: '' })
export class ExampleComponent {
  private readonly nav = inject(NavController);

  openTrail(id: string): void {
    void this.nav.navigateForward(['/trails', id]);
  }
}

navigateForward animates in, navigateBack and back animate out, and navigateRoot replaces the whole stack without a back button, the right choice after a login or when switching top-level sections. The transition style follows the platform mode described in Components and Theming.

Tabs

A tabs page wraps ion-tabs. Each ion-tab-button has a tab name that matches a child route path, and each tab keeps its own navigation stack, so switching away and back restores the previous position:

// src/app/tabs/tabs.page.ts
import { Component } from '@angular/core';
import { IonIcon, IonLabel, IonTabBar, IonTabButton, IonTabs } from '@ionic/angular/standalone';
import { addIcons } from 'ionicons';
import { heart, trailSign } from 'ionicons/icons';

@Component({
  selector: 'app-tabs',
  templateUrl: 'tabs.page.html',
  imports: [IonTabs, IonTabBar, IonTabButton, IonIcon, IonLabel],
})
export class TabsPage {
  constructor() {
    addIcons({ heart, trailSign });
  }
}
<ion-tabs>
  <ion-tab-bar slot="bottom">
    <ion-tab-button tab="trails" href="/trails">
      <ion-icon name="trail-sign"></ion-icon>
      <ion-label>Trails</ion-label>
    </ion-tab-button>
    <ion-tab-button tab="favourites" href="/favourites">
      <ion-icon name="heart"></ion-icon>
      <ion-label>Favourites</ion-label>
    </ion-tab-button>
  </ion-tab-bar>
</ion-tabs>

Pages that should hide the tab bar, such as the log-a-hike form, are declared as routes outside the tabs route, as in the route table above, so they cover the tab bar when pushed.

Page Lifecycle: Why ngOnInit Is Not Enough

Because a page below the top of the stack stays alive, Angular’s own lifecycle does not match what the user sees. ngOnInit runs once, when the component is created; going to the detail page and returning does not run it again, and the page was never destroyed. A list that loads data only in ngOnInit therefore shows stale data after the user returns from logging a hike. Ionic adds lifecycle events that fire on every visit:

Hook When it runs

ionViewWillEnter

Before the page becomes visible, every time, including when returning to it. The place to refresh data.

ionViewDidEnter

After the transition ends. Start animations or focus an input here.

ionViewWillLeave

Before the page starts leaving, whether forward or back. Pause timers and subscriptions here.

ionViewDidLeave

After the page is no longer visible. It may still be in the stack.

In standalone components the hooks are plain methods with these names, which Ionic invokes:

import { Component, inject } from '@angular/core';
import { TrailService } from './trail.service';

@Component({ selector: 'app-trail-list', template: '', })
export class TrailRefreshExample {
  private readonly service = inject(TrailService);

  // Runs once, when the component instance is created.
  ngOnInit(): void {
    console.debug('created');
  }

  // Runs every time the page is shown, including after returning from the detail page.
  ionViewWillEnter(): void {
    void this.service.load();
  }
}

Use ngOnInit for one-time setup and ionViewWillEnter for refreshes. ngOnDestroy runs only when a page is popped from the stack, so cleanup that must happen whenever the page is hidden belongs in ionViewWillLeave.

Route Guards

Guards are normal Angular functional guards. In Trailhead the log-a-hike route requires a signed-in user, and an unauthenticated visitor is redirected to a login page:

// src/app/auth/auth.guard.ts
import { inject } from '@angular/core';
import { CanActivateFn, Router } from '@angular/router';
import { AuthService } from './auth.service';

export const authGuard: CanActivateFn = () => {
  const auth = inject(AuthService);
  const router = inject(Router);
  return auth.isSignedIn() ? true : router.createUrlTree(['/login']);
};

Guards run before the page enters the stack, so a rejected navigation shows no flash of the page. Remember that a guard in a mobile app is a convenience for the user interface: the API still has to authorize every request.

A deep link opens the app on a specific page from outside it: a link in an email, a QR code at a trailhead, or a notification. Custom URL schemes such as trailhead:// work for development, but production apps use universal links on iOS and app links on Android, which are ordinary https:// addresses that the operating system routes to the app when the domain verifies the association. The platform setup of those files and manifest entries is covered on Platform Integration. Once the operating system hands the URL to the app, the Capacitor App plugin reports it with the appUrlOpen event:

sequenceDiagram participant User as Person participant OS as Operating system participant Shell as Native shell participant Plugin as App plugin participant Router as Angular router User->>OS: Tap https://trailhead.example.com/trails/42 OS->>Shell: Open the app with the URL Shell->>Plugin: Deliver the URL Plugin->>Router: appUrlOpen event with the URL Router->>Router: Map the path to trails/42 Router-->>User: TrailDetailPage is shown
// src/app/app.component.ts
import { Component, NgZone, inject } from '@angular/core';
import { Router } from '@angular/router';
import { App, URLOpenListenerEvent } from '@capacitor/app';
import { IonApp, IonRouterOutlet } from '@ionic/angular/standalone';

@Component({
  selector: 'app-root',
  template: '<ion-app><ion-router-outlet></ion-router-outlet></ion-app>',
  imports: [IonApp, IonRouterOutlet],
})
export class AppComponent {
  private readonly router = inject(Router);
  private readonly zone = inject(NgZone);

  constructor() {
    void App.addListener('appUrlOpen', (event: URLOpenListenerEvent) => {
      this.zone.run(() => {
        const url = new URL(event.url);
        if (url.pathname.startsWith('/trails/')) {
          void this.router.navigateByUrl(url.pathname);
        }
      });
    });
  }
}

The handler validates the path before navigating: a deep link is input from outside the app, so only known route prefixes should be accepted. App.getLaunchUrl() returns the URL the app was cold-started with, if any.

The Android Hardware Back Button

On Android the system back button or gesture must pop the Ionic stack. Ionic’s router outlet handles this for routed pages and overlays by default, going back through the history. The Capacitor App plugin adds the backButton event when the app wants to override it, for example to exit when the root page is shown:

import { Injectable, inject } from '@angular/core';
import { Location } from '@angular/common';
import { App } from '@capacitor/app';

@Injectable({ providedIn: 'root' })
export class BackButtonService {
  private readonly location = inject(Location);

  init(): void {
    void App.addListener('backButton', ({ canGoBack }) => {
      if (canGoBack) {
        this.location.back();
      } else {
        void App.exitApp();
      }
    });
  }
}

Registering a backButton listener replaces the default behaviour, so the handler must navigate back itself.

React and Vue

The same concepts exist in the other frameworks, with the same lifecycle semantics:

React Vue

Router

React Router with IonReactRouter and IonRouterOutlet

Vue Router with ion-router-outlet

Lifecycle

useIonViewWillEnter and related hooks

onIonViewWillEnter and related composition functions

Lazy loading

React.lazy and Suspense

Dynamic import() in route definitions