NavController
For examples on the basic usage of NavController, check out the Navigation section of the Component docs.
NavController is the base class for navigation controller components like
Nav
and Tab
. You use navigation controllers
to navigate to pages in your app. At a basic level, a
navigation controller is an array of pages representing a particular history
(of a Tab for example). This array can be manipulated to navigate throughout
an app by pushing and popping pages or inserting and removing them at
arbitrary locations in history.
The current page is the last one in the array, or the top of the stack if we think of it that way. Pushing a new page onto the top of the navigation stack causes the new page to be animated in, while popping the current page will navigate to the previous page in the stack.
Unless you are using a directive like NavPush, or need a specific NavController, most times you will inject and use a reference to the nearest NavController to manipulate the navigation stack.
Injecting NavController
Injecting NavController will always get you an instance of the nearest NavController, regardless of whether it is a Tab or a Nav.
Behind the scenes, when Ionic instantiates a new NavController, it creates an injector with NavController bound to that instance (usually either a Nav or Tab) and adds the injector to its own providers. For more information on providers and dependency injection, see Providers and DI.
Instead, you can inject NavController and know that it is the correct navigation controller for most situations (for more advanced situations, see Menu and Tab).
class MyComponent {
constructor(nav: NavController) {
this.nav = nav;
}
}
Page creation
For more information on the @Page
decorator see the @Page API
reference.
Pages are created when they are added to the navigation stack. For methods
like push(), the NavController takes any component class that is
decorated with @Page
as its first argument. The NavController then
compiles that component, adds it to the app and animates it into view.
By default, pages are cached and left in the DOM if they are navigated away
from but still in the navigation stack (the exiting page on a push()
for
example). They are destroyed when removed from the navigation stack (on
pop() or setRoot()).
Lifecycle events
Lifecycle events are fired during various stages of navigation. They can be
defined in any @Page
decorated component class.
@Page({
template: 'Hello World'
})
class HelloWorld {
onPageLoaded() {
console.log("I'm alive!");
}
onPageWillLeave() {
console.log("Looks like I'm about to leave :(");
}
}
Page Event | Description |
---|---|
onPageLoaded |
Runs when the page has loaded. This event only happens once per page being created and added to the DOM. If a page leaves but is cached, then this event will not fire again on a subsequent viewing. The onPageLoaded event is good place to put your setup code for the page. |
onPageWillEnter |
Runs when the page is about to enter and become the active page. |
onPageDidEnter |
Runs when the page has fully entered and is now the active page. This event will fire, whether it was the first load or a cached page. |
onPageWillLeave |
Runs when the page is about to leave and no longer be the active page. |
onPageDidLeave |
Runs when the page has finished leaving and is no longer the active page. |
onPageWillUnload |
Runs when the page is about to be destroyed and have its elements removed. |
onPageDidUnload |
Runs after the page has been destroyed and its elements have been removed. |
Nav Transition Promises
Navigation transitions are asynchronous, meaning they take a few moments to finish, and the duration of a transition could be any number. In most cases the async nature of a transition doesn't cause any problems and the nav controller is pretty good about handling which transition was the most recent when multiple transitions have been kicked off. However, when an app begins firing off many transitions, on the same stack at roughly the same time, the nav controller can start to get lost as to which transition should be finishing, and which transitions should not be animated.
In cases where an app's navigation can be altered by other async tasks, which may or
may not take a long time, it's best to rely on each nav transition's returned
promise. So instead of firing and forgetting multiple push
or pop
nav transitions,
it's better to fire the next nav transition when the previous one has finished.
In the example below, after the async operation has completed, we then want to transition to another page. Where the potential problem comes in, is that if the async operation completed 100ms after the first transition started, then kicking off another transition halfway through the first transition ends up with a janky animation. Instead, it's best to always ensure the first transition has already finished before starting the next.
// begin the first transition
let navTransition = this.nav.push(SomePage);
// start an async call, we're not sure how long it'll take
someAsyncOperation().then(() => {
// incase the async operation completed faster than the time
// it took to finish the first transition, this logic should
// always ensure that the previous transition has resolved
// first before kicking off the next transition
navTransition.then(() => {
this.nav.push(AnotherPage);
});
});
Instance Members
setRoot(page, params, opts)
Set the root for the current navigation stack.
Param | Type | Details |
---|---|---|
page |
Type
|
The name of the component you want to push on the navigation stack. |
params |
object
|
Any nav-params you want to pass along to the next view. |
opts |
object
|
Any options you want to use pass to transtion. |
Promise
Returns a promise which is resolved when the transition has completed.
setPages(pages, opts)
You can set the views of the current navigation stack and navigate to the last view.
import {Page, NavController} from 'ionic-angular'
import {Detail} from '../detail/detail'
import {Info} from '../info/info'
export class Home {
constructor(nav: NavController) {
this.nav = nav;
}
setPages() {
this.nav.setPages([ {page: List}, {page: Detail}, {page:Info} ]);
}
}
In this example, we’re giving the current nav stack an array of pages. Then the navigation stack will navigate to the last page in the array and remove the previously active page.
By default animations are disabled, but they can be enabled by passing options to the navigation controller.
import {Page, NavController} from 'ionic-angular'
import {Detail} from '../detail/detail'
export class Home {
constructor(nav: NavController) {
this.nav = nav;
}
setPages() {
this.nav.setPages([ {page: List}, {page: Detail} ], {
animate: true
});
}
}
You can also pass any navigation params to the individual pages in the array.
import {Page, NavController} from 'ionic-angular';
import {Info} from '../info/info';
import {List} from '../list/list';
import {Detail} from '../detail/detail';
export class Home {
constructor(nav: NavController) {
this.nav = nav;
}
setPages() {
this.nav.setPages([{
page: Info
}, {
page: List,
params: {tags: 'css'}
}, {
page: Detail,
params: {id: 325}
}]);
}
}
Param | Type | Details |
---|---|---|
pages |
array<Type>
|
An arry of page components and their params to load in the stack. |
opts |
object
|
Nav options to go with this transition. |
Promise
Returns a promise which is resolved when the transition has completed.
push(page, params, opts)
Push is how we can pass components and navigate to them. We push the component we want to navigate to on to the navigation stack.
class MyClass{
constructor(nav:NavController){
this.nav = nav;
}
pushPage(){
this.nav.push(SecondView);
}
}
We can also pass along parameters to the next view, such as data that we have
on the current view. This is a similar concept to to V1 apps with $stateParams
.
class MyClass{
constructor(nav:NavController){
this.nav = nav;
}
pushPage(user){
// user is an object we have in our view
// typically this comes from an ngFor or some array
// here we can create an object with a property of
// paramUser, and set its value to the user object we passed in
this.nav.push(SecondView, { paramUser: user });
}
}
We’ll look at how we can access that data in the SecondView
in the
navParam docs.
We can also pass any options to the transtion from that same method.
class MyClass{
constructor(nav: NavController){
this.nav = nav;
}
pushPage(user){
this.nav.push(SecondView,{
// user is an object we have in our view
// typically this comes from an ngFor or some array
// here we can create an object with a property of
// paramUser, and set it's value to the user object we passed in
paramUser: user
},{
// here we can configure things like the animations direction or
// or if the view should animate at all.
direction: 'back'
});
}
}
Param | Type | Details |
---|---|---|
page |
Type
|
The page component class you want to push on to the navigation stack |
params |
object
|
Any nav-params you want to pass along to the next view |
opts |
object
|
Nav options to go with this transition. |
Promise
Returns a promise which is resolved when the transition has completed.
present(enteringView, opts)
Present is how app display overlays on top of the content, from within the
root level NavController
. The present
method is used by overlays, such
as ActionSheet
, Alert
, and Modal
. The main difference between push
and present
is that present
takes a ViewController
instance, whereas
push
takes a Page
component class. Additionally, present
will place
the overlay in the root NavController’s stack.
class MyClass{
constructor(nav: NavController) {
this.nav = nav;
}
presentModal() {
let modal = Modal.create(ProfilePage);
this.nav.present(modal);
}
}
Param | Type | Details |
---|---|---|
enteringView |
ViewController
|
The component you want to push on the navigation stack. |
opts |
object
|
Nav options to go with this transition. |
Promise
Returns a promise which is resolved when the transition has completed.
insert(insertIndex, page, params, opts)
Inserts a view into the nav stack at the specified index. This is useful if you need to add a view at any point in your navigation stack.
export class Detail {
constructor(nav: NavController) {
this.nav = nav;
}
insertPage(){
this.nav.insert(1, Info);
}
}
This will insert the Info
page into the second slot of our navigation stack.
Param | Type | Details |
---|---|---|
insertIndex |
number
|
The index where to insert the page. |
page |
Type
|
The component you want to insert into the nav stack. |
params |
object
|
Any nav-params you want to pass along to the next page. |
opts |
object
|
Nav options to go with this transition. |
Promise
Returns a promise which is resolved when the transition has completed.
insertPages(insertIndex, insertPages, opts)
Inserts multiple pages into the nav stack at the specified index.
export class Detail {
constructor(nav: NavController) {
this.nav = nav;
}
insertPages(){
let pages = [
{ page: Info },
{ page: ProfileList },
{ page: ProfileDetail, params: {userId:5} }
];
this.nav.insertPages(2, pages);
}
}
This will insert each of the pages in the array, starting at the third slot (second index) of the nav stack. The last page in the array will animate in and become the active page.
Param | Type | Details |
---|---|---|
insertIndex |
number
|
The index where you want to insert the page. |
insertPages |
array<{page: Type, params=: any}>
|
An array of objects, each with a |
opts |
object
|
Nav options to go with this transition. |
Promise
Returns a promise which is resolved when the transition has completed.
pop(opts)
If you wanted to navigate back from a current view, you can use the
back-button or programatically call pop()
. Similar to push()
, you
can also pass navigation options.
class SecondView{
constructor(nav:NavController){
this.nav = nav;
}
goBack(){
this.nav.pop();
}
}
Param | Type | Details |
---|---|---|
opts |
object
|
Nav options to go with this transition. |
Promise
Returns a promise which is resolved when the transition has completed.
popToRoot(opts)
Similar to pop()
, this method let’s you navigate back to the root of
the stack, no matter how many pages back that is.
Param | Type | Details |
---|---|---|
opts |
object
|
Nav options to go with this transition. |
Promise
Returns a promise which is resolved when the transition has completed.
popTo(view, opts)
Pop to a specific view in the history stack.
Param | Type | Details |
---|---|---|
view |
ViewController
|
to pop to |
opts |
object
|
Nav options to go with this transition. |
Promise
Returns a promise which is resolved when the transition has completed.
remove(startIndex, removeCount, opts)
Removes a page from the nav stack at the specified index.
export class Detail {
constructor(nav: NavController) {
this.nav = nav;
}
removePage(){
this.nav.remove(1);
}
}
Param | Type | Details |
---|---|---|
startIndex |
number
|
The starting index to remove pages from the stack. Default is the index of the last page. |
removeCount |
number
|
The number of pages to remove, defaults to remove |
opts |
object
|
Any options you want to use pass to transtion. |
Promise
Returns a promise which is resolved when the transition has completed.
canSwipeBack()
If it’s possible to use swipe back or not. If it’s not possible
to go back, or swipe back is not enabled, then this will return false
.
If it is possible to go back, and swipe back is enabled, then this
will return true
.
boolean
canGoBack()
Returns true
if there’s a valid previous page that we can pop
back to. Otherwise returns false
.
boolean
isTransitioning()
Returns if the nav controller is actively transitioning or not.
boolean
getByIndex(index)
Param | Type | Details |
---|---|---|
index |
number
|
The index of the page to get. |
ViewController
Returns the view controller that matches the given index.
getActive()
ViewController
Returns the active page's view controller.
isActive(view)
Param | Type | Details |
---|---|---|
view |
ViewController
|
boolean
getPrevious(view)
Returns the view controller which is before the given view controller.
Param | Type | Details |
---|---|---|
view |
ViewController
|
viewController
first()
Returns the first view controller in this nav controller’s stack.
ViewController
last()
Returns the last page in this nav controller’s stack.
ViewController
indexOf(view)
Returns the index number of the given view controller.
Param | Type | Details |
---|---|---|
view |
ViewController
|
number
length()
Returns the number of views in this nav controller.
number
The number of views in this stack, including the current view.
rootNav
Returns the root NavController
.
NavController