⚠️ This lesson is retired and might contain outdated information.

Use Ionic 2 NavController to Manipulate App History

Mike Hartington
InstructorMike Hartington
Share this video with your friends

Social Share Links

Send Tweet
Published 8 years ago
Updated 9 months ago

Ionic’s NavController offers an extensive API that allows you to manipulate your apps history, create history from nothing, and programmatically navigate back. NavController has an extensive API with many methods and lifecycle hooks that developers can use. Be sure to check out the documentation

[00:01] Unlike a traditional Angular app, Ionic apps use a NavController for handling routes and views. NavController provides a full API for working with app history, instead of relying on the browser and URLs for navigating around.

[00:15] To set up NavController, we first create a base ion nav component. Then we set a root property. The root property is a dynamic input, and we set its value to the home page component in our base class. With this, we've created an instance of NavController.

[00:31] Now, we can start calling methods on the NavController to start to navigate around our app. For example, from our home page class, we import NavController, inject it into our constructor, and then call push to navigate to a new page.

[00:49] If we want to go back programmatically, we could call pop on the NavController. We'll open up our detail page. Inside of the constructor, we'll add a set timeout.

[01:03] Inside of that, we'll call this.NavController.pop. Then we'll set the time for the timeout to two seconds.

[01:13] When we navigate to the detail page, we'll wait two seconds, and then NavController.pop will be called. We could think about the navigation stack as an array of components. Push will add a new component to the stack, and pop will remove the current component from the stack.

[01:29] Another advantage of NavController is its ability to create app history from nothing. In home.ts, instead of calling push, let's call setPages instead. Now, setPages takes an array of objects with a page property, and then an optional params property.

[01:50] For our array, we'll set a home page, then a detail page, grabbing a random user. We'll set the home page again, and then the detail page again, but with the user being passed in. Now, when we click on our item, we'll navigate to the last detail page, and then have app history to navigate back through.

[02:25] The NavController API is quite extensive, so be sure to check out the docs for all the available methods.