Ionic 2 makes it easy to create mutiple pages navigation using NavController
as the genesis of navigation stack. In this little application, I will try to make the concept clear to you.
To start with, let's create a new Ionic app for this showcase. Follow along with me. To get started, we have to scaffold a new project, my favorite one-to-go Ionic CLI command:
https://gist.github.com/8c5e33e7423be5b5eab4a7eac3251f28
cd
in to the new project created by the above Ionic CLI command and run ionic serve
to see the blank template with just a homepage available. We will create two new pages in this application to showcase our motive.
To read about the basic Navigation in an Ionic app, see this.
Now, with the help of Ionic CLI, let's generate two new pages before diviing into our code base.
https://gist.github.com/de0f5ac3505c21c4385a561a2c877306
I am naming the two new pages generic but you can name them anything you want. Just follow the convention when importing the modules. Inside the app/pages
you can see, there are two new folders with the names we generated. Each have its own .ts
, .html
and .scss
file, thus, completing a web component on which every Ionic and Angular apps are based on.
To proceed, we need to add both the pages in our app.module.ts
:
https://gist.github.com/f45fff4303c11aa0f3c634a0bd1b0be1
As the app.module.ts
is updated with our changes, the scope of the whole application can now access these two new pages. To implement the navigation between them, we have to first update our home.html
with buttons that will navigate to a specific page and business logic behind those events in home.ts
.
https://gist.github.com/ec8565bb4120d1847ea2eb3dd33cdf63
Let's update home.ts
as well.
https://gist.github.com/7669b3f264c4a4e9b9c6389c476bcf53
The goTo()
function will help us in navigating to the desired page and back
button will bring us to the previous page in the navigation stack. This is important! I mentioned to the previous page, not the home page. If you are familiar with Ionic 1, this would how state will work.
To continue to develop our demo application, we need to update our Page1
and Page2
components.
https://gist.github.com/eaa66a8e265d709a0cdf9e28015d5583
https://gist.github.com/4eb3db8e5346f05129b5d11688956905
Similar for the Page2
:
https://gist.github.com/495a86e55f0bd61e7ca5cd2b31f2edad
https://gist.github.com/5b99ac8daa3b1d3cae7172268bf3e03d
If we save all the files and again from the terminal run:
https://gist.github.com/15ceaf99fdc329f75fe2643335cda829
The output shown can be best described in these screenshots:
This is just a glimpse of how multi page navigation in Ionic might work.
To get the full code, you can visit this Github Repository