Navigation in Ionic works like a simple stack, where we push new pages onto the top of the stack, which takes us forwards in the app. To go backwards, we pop the top page off. Using push to navigate to a new page is simple, and Ionic’s navigation system is very flexible.
You don't have to implement a stack by yourself, Ionic 3 has already done that for you. You can easily accomplish navigation by using the NavController component which is injected into every page constructor alongside many other components.
The NavController component exposes many methods so you can control the navigation stack but NavController is not the only available component for navigation, there are other components:push() method :
import { AboutPage } from '../about/about';
import { ContactPage } from '../contact/contact';
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
constructor(public navCtrl: NavController) { }
public gotoAbout(){
this.navCtrl.push(AboutPage);
}
public gotoContact(){
this.navCtrl.push(ContactPage);
}
}
<button ion-button (click)='gotoAbout();'>Go to about</button>
<button ion-button (click)='gotoContact()'>Go to contact</button>
pop() method :
goBack(){
this.navCtrl.pop();
}
In many situations we need to pass parameters from one page to another for example from a list page to a detail page.
You can pass parameters with the push() method of NavController as the second parameter of the method and retrieve them by injecting NavParams.
gotoAbout(){
this.navCtrl.push(this.aboutPage,{param1 : "hello" , param2 : "world"});
}
import { NavParams } from 'ionic-angular';
Injecting service and retrieving parameters
@Component({
selector: 'page-about',
templateUrl: 'about.html'
})
export class AboutPage {
private param1 : string ;
private param2 : string ;
private allParams ;
constructor(public navCtrl: NavController, public navParams: NavParams) {
this.param1 = this.navParams.get("param1");
this.param2 = this.navParams.get("param2");
this.allParams = this.navParams.data ;
}
}
<ion-nav [root]='rootPage'></ion-nav>
@Component({
templateUrl: 'app.html'
})
export class MyApp {
rootPage = HomePage;
}
this.navCtrl.setRoot(HomePage);
<ion-header>
<ion-navbar>
<ion-title>
Ionic Blank
</ion-title>
</ion-navbar>
</ion-header>
<ion-header>
<ion-navbar>
<ion-title>
Ionic 2 navigation demo
</ion-title>
</ion-navbar>
<ion-buttons end>
<button ion-button icon-only (click)='openModal()'>
<ion-icon name="options"></ion-icon>
</button>
</ion-buttons>
</ion-header>