Our website is made possible by displaying online advertisements to our visitors. Please consider supporting us by disabling your ad blocker.

Navigating A NativeScript App With The Angular Router

TwitterFacebookRedditLinkedInHacker News

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 in full force, it probably makes sense to demonstrate navigation with the very different Angular Router component.

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

We’re going to take a look at simple navigation between two Angular components in a NativeScript Android and iOS mobile application using the now stable Angular 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:

tns create MyProject --ng
cd MyProject
tns platform add ios
tns platform add android

Note that the --ng tag indicates an Angular project, not a vanilla NativeScript project. This means we’ll be using TypeScript and Angular. 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:

mkdir -p components/page1
mkdir -p components/page2
touch components/page1/page1.ts
touch components/page1/page1.html
touch components/page2/page2.ts
touch components/page2/page2.html

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:

import {Component} from "@angular/core";

@Component({
    selector: "page2",
    templateUrl: "./components/page2/page2.html",
})
export class Page2Component {

    public constructor() {}

}

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:

<ActionBar title="Page 2">
    <NavigationButton text="Back"></NavigationButton>
</ActionBar>
<StackLayout>
</StackLayout>

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:

import {Component} from "@angular/core";
import {Router} from "@angular/router";

@Component({
    selector: "page1",
    templateUrl: "./components/page1/page1.html",
})
export class Page1Component {

    public constructor(private router: Router) {

    }

    public onTap() {
        this.router.navigate(["page2"]);
    }

}

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 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:

<ActionBar title="Page 1">
    <ActionItem text="Next" ios.position="right" (tap)="onTap()"></ActionItem>
</ActionBar>
<StackLayout>
</StackLayout>

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:

import { Page1Component } from "./components/page1/page1";
import { Page2Component } from "./components/page2/page2";

export const appRoutes: any = [
    { path: "", component: Page1Component },
    { path: "page2", component: Page2Component }
];

export const appComponents: any = [
    Page1Component,
    Page2Component
];

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:

// this import should be first in order to load some required settings (like globals and reflect-metadata)
import { platformNativeScriptDynamic, NativeScriptModule } from "nativescript-angular/platform";
import { NgModule } from "@angular/core";
import { AppComponent } from "./app.component";
import { NativeScriptRouterModule } from "nativescript-angular/router";
import { appComponents, appRoutes } from "./app.routing";

@NgModule({
    declarations: [AppComponent, ...appComponents],
    bootstrap: [AppComponent],
    imports: [
        NativeScriptModule,
        NativeScriptRouterModule,
        NativeScriptRouterModule.forRoot(appRoutes)
    ],
})
class AppComponentModule {}

platformNativeScriptDynamic().bootstrapModule(AppComponentModule);

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:

<page-router-outlet></page-router-outlet>

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:

{ path: "page2/:name", component: Page2Component }

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:

this.router.navigate(["page2", "Nic Raboy"]);

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:

import {Component} from "@angular/core";
import {ActivatedRoute} from "@angular/router";

@Component({
    selector: "page2",
    templateUrl: "./components/page2/page2.html",
})
export class Page2Component {

    public fullName: string;

    public constructor(private route: ActivatedRoute) {
        this.route.params.subscribe((params) => {
            this.fullName = params["name"];
        });
    }

}

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:

<ActionBar title="Page 2">
    <NavigationButton text="Back"></NavigationButton>
</ActionBar>
<StackLayout>
    <Label text="Hello {{fullName}}"></Label>
</StackLayout>

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 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 Raboy

Nic Raboy is an advocate of modern web and mobile development technologies. He has experience in C#, JavaScript, Golang and a variety of frameworks such as Angular, NativeScript, and Unity. Nic writes about his development experiences related to making web and mobile development easier to understand.