How to conditionally set the root page of an Ionic app

The rootpage of an Ionic app is the first page that is displayed after the root component (normally app.component.ts). The rootpage is the start of the app navigation and is always the first element in the navigation stack. It can be navigated to like this after the app is initialized and running:

@Component(....)
class MyComponent {
  constructor(navCtrl: NavController){}

  gotoRoot() {
    this.navCtrl.setRoot(MyAwesomePage); //sets a new rootPage and navigates there
  }

  poptoRoot() {
    this.navCtrl.popToRoot();  //return to the existing rootPage and navigate there
  }
}

The first rootpage upon app initialization is set in the AppComponent that belongs to the (root) AppModule. In the docs its only mentioned that you define the rootPage as a quasi static property of the AppComponent like this example taken directly from the Ionic documentation:

@Component(
  template: `<ion-nav [root]="rootPage"></ion-nav>`
})
class MyApp {
  // set the rootPage to the first page we want displayed
  public rootPage: any = StartPage;

  constructor(){
  }
}

Its not mentioned anywhere, but you can also define rootPage lazy and conditionally, like f.i. when you have a local database and want to first initialize the database driver and look into it to check if the user is already logged in or not. Depending on the result you want to display a LoginPage as the rootpage or your normal standard page for users.

That is done almost always asynchronous so you can’t define the rootPage in the constructor of your AppComponent because you don’t know it yet.

In this case you can leave the rootPage uninitialized and just set it later. Ionic automatically grabs any changes and navigates to the rootPage:

@Component(
  template: `<ion-nav [root]="rootPage"></ion-nav>`
})
class MyApp {
  // don't set the rootPage initially to anything
  public rootPage: any

  constructor(private userService: UserService){
    this.userService.initDatabaseAndUser().subscribe(user => {
      if (user.isLoggedIn) {
        this.rootPage = StartPage;
      } else {
        this.rootPage = LoginPage;
      }
    }
  }
}

Leave a Reply

Your email address will not be published. Required fields are marked *

*