Navigating A NativeScript App With The Angular 2 Router

Unless you want a very boring single page application, you’re going to want some form of page navigation with multiple pages available.  Previously I wrote a tutorial for navigating between routes in a vanilla JavaScript NativeScript application, but with Angular 2 in full force, it probably makes sense to demonstrate navigation with the very different Angular 2 Router component.

Anyone who has been following Angular 2 since beta knows that the navigation components have changed drastically in pretty much every release.  Anyone who has been following NativeScript and Angular 2 knows that Telerik likes to use any and all Angular 2 in its vanilla state.  This means that navigation in NativeScript Angular 2 applications has changed quite a bit over the past year.  However, with Angular 2 now in general availability (GA), the Angular 2 Router is no longer beta and should no longer be changing.

We’re going to take a look at simple navigation between two Angular 2 components in a NativeScript Android and iOS mobile application using the now stable Angular 2 Router.

To make this guide easy to follow, we’re going to create a fresh NativeScript Android and iOS project.  From the Command Prompt (Windows) or Terminal (Mac and Linux), execute the following:

Note that the --ng tag indicates an Angular 2 project, not a vanilla NativeScript project.  This means we’ll be using TypeScript and Angular 2.  Also note that if you’re not using a Mac with Xcode installed, you won’t be able to build for iOS.

This particular project will make use of two different navigation routes, both of which are not included in the base NativeScript template.  Create the following in the app directory of your project:

If your command line doesn’t have mkdir and touch or you don’t feel comfortable using them, go ahead and create those files and directories manually.

Let’s focus on the second page of our application first, or in other words, the page that we plan to navigate to.

Open the project’s app/components/page2/page2.ts file and include the following code:

There isn’t anything special in the above TypeScript code.  Essentially we are just saying that the TypeScript code is bound to the corresponding HTML file.  Having created the Page2Component class is important though.

With the TypeScript out of the way for the second page, open the project’s app/components/page2/page2.html file so we can add some UI markup:

In the above markup, all we’re doing is creating a navigation bar with a back button and an empty layout.  However, the navigation bar title is more than enough to tell us that we’ve navigated away from the first and default page.

With the second page out of the way, we can now focus on the first page which will be the default page when the application opens.

Open the project’s app/components/page1/page1.ts file and include the following TypeScript code:

Without getting too far ahead of ourselves, this TypeScript file looks very similar to that of the second page.  However, we’ve included an onTap method and imported the Angular 2 Router component.  After having injected the Router in the constructor, we can use it to navigate to any of our available routes.

We’ve not yet defined our routes, but it is safe to assume that page2 represents our second page.  We’ll get to that in a minute.

Open the project’s app/components/page1/page1.html file and include the following HTML markup:

Notice in the above HTML we have a navigation button that triggers the onTap method when clicked?  This is how the navigation is triggered.

We’re not done yet.  Remember how I mentioned that we haven’t defined our available routes?  We need to define those routes now.

Create an app/app.routing.ts file in your project.  Within this file, the following code should exist:

Notice that we’ve imported all available pages at the top?  We can establish available routes within the appRoutes array where the path represents the value used in the TypeScript navigation and the component being the corresponding component to the path.

To save us some time in the next step, we construct an array of every available component as well.

The next step would be to include this route information in the all-powerful @NgModule block found in the project’s app/main.ts file.  The file would look something like this:

We’ve imported the NativeScriptRouterModule and the constant variables that we had just defined in the app/app.routing.ts file.

In the @NgModule block we declare all components found in the appComponents array in the declarations property.  We also import the NativeScriptRouterModule and available routes in the imports property.

We’re almost done!

The fine step would be to determine where these routes become visible on the screen.  Open the project’s app/app.component.html file and exchange all the HTML markup with the following:

At this point if you tried to run your application, navigation between the two pages should work.

Passing Parameters Between Routes

Now what happens if you want to pass some data between routes?  A solid example of this would be passing in an id from a list and then querying that id in the second page.

Let’s make a few modifications to make this possible.

Open the project’s app/app.routing.ts file and change the following line:

Notice that we’ve added /:name to the path?  This is because we plan to pass a variable representing a name.

To pass this data from the first page, open the project’s app/components/page1/page1.ts file and change the navigation command so it looks like the following:

In the above example we are passing a string representing my name with the navigation request.  On the second page we need to anticipate a value and retrieve it.

Open the project’s app/components/page2/page2.ts file and change the code to match the following:

To receive data from a parent page, the ActivatedRoute component must be imported.  Within the constructor method we’ve subscribed to the navigation parameters and assigned them to the fullName variable.  We can then display that variable in the UI.

Open the project’s app/components/page2/page2.html and include the following HTML markup:

The screen should say “Hello Nic Raboy” when you navigate to it.

Conclusion

We just saw how to use the latest stable release of the Angular 2 Router for handling navigation between pages in a NativeScript Android and iOS mobile application.  Not only did we handle navigation between pages, but we also accommodated the scenario where we need to pass a parameter of data to a page.

This tutorial was a followup to the vanilla NativeScript with JavaScript tutorial that I wrote not too long ago.

A video version of this article can be seen below.

Nic Raboy

Nic is a skilled application developer who has released several native and hybrid mobile applications to iTunes and Google Play. He writes about his development experiences related to making web and mobile app development easier to understand and has experience in Android, Node.js, Apache Cordova, Java, NoSQL, SQL, GoLang, NativeScript, and Unity3D.

  • Davor Peić

    Hey, as we chatted on twitter, this tutorial would be great if you could expand passing a parameter with “Passing data object between routes” for cases where we already have data downloaded on the page1 and want to pass it to page2. Either way thanks for great tutorial!

  • Herman

    Hi Nic, I got a question. When I’m trying to run my app I’ve got this error:

    app/app.routing.ts(1,32): error TS2307: Cannot find module ‘./components/page1/page1’.

    app/app.routing.ts(2,32): error TS2307: Cannot find module ‘./components/page2/page2’.

    • Herman

      I got it… I needed to rebuild the project with “../components/page1/page1” and “../components/page1/page1”
      Thanks anyway.

      • Herman

        Nope, same thing… 🙁

        • Verify your placement of the app.routing.ts file as well as the two files that you’re trying to import. I’ve made the mistake before where I created those files in the wrong directory (parent or child) and didn’t realize it.

          The tutorial is still valid, likewise with the YouTube video I made for it. My best guess is your file placement.

          • Herman

            Yeah, you’re right I’ve created the folder in the wrong place. That one is solved, but now when I run the app I got this errors:
            W/System.err( 2651): at com.tns.Runtime.callJSMethodNative(Native Method)
            W/System.err( 2651): at com.tns.Runtime.dispatchCallJSMethodNative(Runtime.java:865)
            W/System.err( 2651): at com.tns.Runtime.callJSMethodImpl(Runtime.java:730)
            W/System.err( 2651): at com.tns.Runtime.callJSMethod(Runtime.java:716)
            W/System.err( 2651): at com.tns.Runtime.callJSMethod(Runtime.java:697)
            W/System.err( 2651): at com.tns.Runtime.callJSMethod(Runtime.java:687)

          • Herman
          • Just tested it again on my end and it works fine for me. Based on your error regarding the page-router-outlet, I imagine that you’re not importing or injecting the right things in your main.ts file.

            I recommend going through the tutorial again.

            I’m using the latest version of NativeScript as of now which is 2.3.0

            Best,