blackHawk
blackHawk

Reputation: 6307

Ionic 2: Navigating from the Root Component

What does it mean?

What if you want to control navigation from your root app component (the one decorated with @App, not @Page)? You can’t inject NavController because any components that are navigation controllers are children of the root component so they aren’t available to be injected.

By adding an id to ion-nav, you can use the IonicApp service to get a reference to the Nav component, which is a navigation controller (it extends NavController):

Upvotes: 2

Views: 3936

Answers (3)

kanishkamehta
kanishkamehta

Reputation: 1

To navigate from the root component, first you have to get the component and then set it again, see the example below:

this.app.getRootNav().setRoot( VisitorsPage );

Upvotes: 0

Ryan Loggerythm
Ryan Loggerythm

Reputation: 3314

Keep in mind that pages and components are not the same thing.

Your pages all import NavController, so there is no need to hack the DOM!! :) Your current page is capable of pushing any other page on top of itself, so long as you imported that page (the current page needs to know of the existence of the page to push).

this.nav.push(OtherPage);

Similarly, the current page can pop itself off from view.

this.nav.pop();

It can even change the root view directly.

this.nav.setRoot(OtherPage);

Lastly, this Simple guide to navigation in ionic2 will explain it all very well...

Upvotes: 0

sebaferreras
sebaferreras

Reputation: 44659

Just in case if this could help other developers, and since in Ionic2 beta 8

@App and @Page should be replaced with @Component.

Now you should be able to navigate from the root component by doing something like this:

import {Component, ViewChild, provide, PLATFORM_DIRECTIVES} from '@angular/core';
import {ionicBootstrap, App, Platform, MenuController, Nav} from 'ionic-angular';
import {StatusBar} from 'ionic-native';
import {HomePage} from './pages/home/home';

@Component({
  templateUrl: 'build/app.html'
})
class MyApp {
  @ViewChild(Nav) nav: Nav;

  rootPage: any = HomePage;

  constructor(private platform: Platform, private menu: MenuController) {
    this.initializeApp();
  }

  initializeApp(): void {
    this.platform.ready().then(() => {
      // Okay, so the platform is ready and our plugins are available.
      // Here you can do any higher level native things you might need.
      StatusBar.styleDefault();
    });
  }

  openPage(aPage: any) {
    // close the menu when clicking a link from the menu
    this.menu.close();

    // navigate to the new page if it is not the current page
    this.nav.setRoot(aPage);
  }
}

ionicBootstrap(MyApp, [], {
  //config options
});

Upvotes: 1

Related Questions