Navigation
http://ionicframework.com/docs/v2/components/#navigation
更多深入的导航用法,请参考API文档。
Navigation控制App内不同的页面间进行转换。Ionic的Navigation遵循各原生平台的导航原则。为了使导航更像原生导航,我们建立了几个新的导航组件,对开发者来说可能会感觉与传统桌面浏览器导航不太一样。
这里是几种Ionic App进行导航的方式:
基本用法
Navigation是在ion-nav组件内进行处理的,像一个简单的栈,页面被push或被pop,就可以实现向前导航或历史栈的后退导航。
首先从一个Nav组件中设置的root page开始:
import {StartPage} from 'start'
@Component({
template: '<ion-nav [root]="rootPage"></ion-nav>'
})
class MyApp {
// First page to push onto the stack
rootPage = StartPage;
}
接下来,我们在每个页面中注入Navigation Controller。注意Page组件不需要selector,Ionic会自动添加它们。
依赖注入的概念请自行参考
Angular 2相关文档。简单来说,我们要在页面内用哪个组件,就可以将其注入进来,方法就是在Page的构造函数中引入相应的变量。
@Component({
template: `
<ion-header>
<ion-navbar>
<ion-title>Login</ion-title>
</ion-navbar>
</ion-header>
<ion-content>Hello World</ion-content>`
})
export class StartPage {
constructor(public navCtrl: NavController) {
}
}
为了导航到另一个页面,只需要简单的在栈中push或pop即可:
@Component({
template: `
<ion-header>
<ion-navbar>
<ion-title>Login</ion-title>
</ion-navbar>
</ion-header>
<ion-content>
<button (click)="goToOtherPage()">
Go to OtherPage
</button>
</ion-content>`
})
export class StartPage {
constructor(public navCtrl: NavController) {}
goToOtherPage() {
//push another page onto the history stack
//causing the nav controller to animate the new page in
this.navCtrl.push(OtherPage);
}
}
@Component({
template: `
<ion-header>
<ion-navbar>
<ion-title>Other Page</ion-title>
</ion-navbar>
</ion-header>
<ion-content>I'm the other page!</ion-content>`
})
class OtherPage {}
如果页面中有<ion-navbar>并且该页面不是root page,那么将会自动显示一个后退按钮,NavBar的标题也会自动更新。
如果你没有使用NavBar,想要返回前一页的时候,可以把当前页面从栈中pop出去:
@Component({
template: `
<ion-content>
<button (click)="goBack()"> There's no place like home
</button>
</ion-content>`
})
class OtherPage {
constructor(public navCtrl: NavController) {}
goBack() {
this.navCtrl.pop();
}
}
从根组件导航
如何从根组件控制导航?你不能注入NavController因为任何Navigation Controller组件都是根组件的Children,所以它们不能被注入进来。
通过给ion-nav添加一个引用变量,你可以使用@ViewChild来获得Nav组件的一个实例,它其实就是一个Navigation Controller(但扩展了NavController):
@Component({
template: '<ion-nav #myNav [root]="rootPage"></ion-nav>'
})
export class MyApp {
@ViewChild('myNav') nav
rootPage = TabsPage;
// Wait for the components in MyApp's template to be initialized
// In this case, we are waiting for the Nav identified by
// the template reference variable #myNav
ngAfterViewInit() {
// Let's navigate from TabsPage to Page1
this.nav.push(LoginPage);
}
}
Tabbed Navigation
Navigation可以用在像Tabs之类的复杂组件里。与传统的路由系统不同,Ionic的导航系统使App内的导航非常简单,不需要指定特定的路由。比如为了使用iOS的App Store App,我们可以简单的从任意tab导航到AppDetailPage来显示关于一个特定App的信息。看一下Tabs的文档获取更多信息,了解如何简单的使用导航。