Search code examples
angulartypescriptionic-frameworkionic2ionic2-tabs

How can I set a root page outside of tabs that don't keep the tabs in place?


The flow of my app means that there are no tabs in place until a user logs in. The first page is a full-screen login screen. Once logged in the user is taken to tabs.ts which holds my tabs code.

One of the tabs has a button in that logs users out:

user.ts:

  // Logout
  logout() {    
    // Log the user out
    this.user.logout();

    // Take user to login screen
    this.navCtrl.setRoot(LoginPage);
  }

I thought that setting the root to LoginPage, which isn't part of any tab page, would remove the tabs. Unfortunately not, and the tabs remain. This is really problematic for obvious reasons.

How can I remove the tabs from this point? I feel like I need to potentially grab the tabs instance and destroy it, but that's a guess and I'm struggling to find anything in the docs.


Solution

  • After posting this I found the answer on the Ionic forums.

    Effectively, each tab maintains its own navigation stack, which I was aware of but I expected the setRoot to bypass the stack. Logically, it does not.

    Instead, you need to call getRootNav().setRoot() on your App.

    App is imported from ionic-angular, and then passed to your controller.

    A full (albeit truncated) example:

    import { Component } from '@angular/core';
    import { App } from 'ionic-angular';
    
    @Component({
      selector: 'page-profile',
      templateUrl: 'profile.html'
    })
    export class ProfilePage {
    
      constructor(
        private app: App
      ) {
    
      }
    
      // Logout
      logout() {
        // Take user to login screen
        this.app.getRootNav().setRoot(LoginPage);
      }
    
    }