Removing a Page or Modal From The Navigation Stack in Ionic Framework 2

In mobile apps it is frequent to have a combination of the following screens:

  • ListPage - a page that lists items and links to each item's details page
  • DetailsPage - a page that shows more details about an item
  • ComposeModal - a modal/page with a form to create a new item

When a user taps on one of the items on the list, and then click the back button they expect to go back to the list:

ListPage -> DetailsPage
ListPage <- DetailsPage

When a user creates a new item using the ComposeModal, they are taken to the details page after the item was created. When they tap the back button, they expect to go back to the list page, not to the ComposeModal.

ListPage -> ComposeModal -> DetailsPage
ListPage <- DetailsPage

In ionic 2, the navigation works as a stack. Each new page is pushed on top of the previous one. So when the user taps the back button from the DetailsPage after creating a new item, they will be taken back to the compose page instead of the ListPage.

To avoid this, we need to remove the ComposeModal from the stack after a new item is created and after the transition animation to the DetailsPage has completed. This can be done using NavController.

import {ViewController, NavController} from 'ionic-angular';

  template: `
      ... form ...
      <button (click)="createItem()"></button>
class ComposeModal {

  constructor(private nav: NavController, private viewCtrl: ViewController) {}

  createItem() {

    // ... create item here. Then, handle the navigation

      .then(() => {
        // first we find the index of the current view controller:
        const index = this.viewCtrl.index;
        // then we remove it from the navigation stack



ComposeModal will be removed from the stack only after the transition has completed and DetailsPage is shown so the user won't notice that is was removed and the back button will work as expected.

Follow me for updates on similar new posts I write or tweet about this post.