Javascript

Routing your Angular 2 Application

November 18th, 2016 | By Thomas Greco | 6 min read

In the first article of this series, we learned how to build our first application with Angular 2.0. Specifically, we learned about the building blocks of the framework – components and modules – and the role they play in development.

In this article, we’re going to expand upon this knowledge by taking a look at the Angular 2.0 framework’s router. To successfully do so, we’re going to build upon the application built in part of this three parts series, and route to a few additional components that our sample application included.

By the end of this tutorial, we’ll have taken a look at the core-concepts behind routing in Angular 2.0 while also focusing on the best practices to ensure we build the best coding-habits as possible! Those who wish to follow along can find the code for this tutorial at this GitHub repository

Below, we can see a finished version of our example.

Note on External Components

By taking a look at the plnkr, we’ll see that the application created in the first article in this series has three additional components: HomeComponent, AboutComponent, ContactComponent. As said above, this article will deal strictly with routing while the first article in this series discusses component creation, so those interested should check that article out. Now, let’s move ahead and learn about routing our single page application.

Configuring Our Routes

To follow Angular 2.0′s best practices, we want to place our route configuration into a special app.routes.ts file. Inside this file, we need to import the RouterModule in addition to any component that’s we wish to route to. Once we’re done configuring our routes, we’ll use RouterModule to tell Angular about them.

Importing Necessary Assets

In our example, our import statements will look like the following.

// src/app.routes.ts
/* Import Routes Config */
import {
RouterModule
}
from '@angular/router';
/* Import Individual Component */
import {
HomeComponent
}
from './home.component';
import {
AboutComponent
}
from './about.component';
import {
ContactComponent
}
from './contact.component';

Protect your Angular App with Jscrambler

Configuring Route Definitions

Once we have access to the necessary imports, we can establish our route definitions. In our example, these route definitions will be held within a const named routes. We use this array to encapsulate all of the configuration for our different routes, namely the path and the component.

// src/app.routes.ts
const routes = [{
path: '',
component: HomeComponent
}, {
path: 'about',
component: AboutComponent
}, {
path: 'contact',
component: ContactComponent
}];

Above, we can see how we assign a path and a component for each route. The path is simply the name Angular will use to build the URL, while the component ties this URL to a specific component.

Our code routes our application to the following:

  1. HomeComponent:

  • This will load when the URL has no appending string (/).
    In our example, we are telling Angular that we want our HomeComponent to load automatically by giving it the empty value with the string ''.

  1. AboutComponent :

  • This will load when the URL points to /about.

  1. ContactComponent:

  • This will load when the URL points to /contact.

By default, Angular 2 will load routes with a /#/ prefix, therefore our routes will look like the following : /#/, /#/about, /#/contact. As we learned before, our HomeComponent has an empty path, which means that it is going to load automatically. this shows how Angular 2 makes the process of creating nested child-routes a breeze, which can be extremely helpful as applications grow bigger.

Exporting routes as default class

Before we continue forward and add our routes to our main AppModule, let’s take a look at the final piece of code inside this file: the export statement.

// src/app.routes.ts
/*
* const routes = [
* Route Config ...
* ]
**/
export default RouterModule.forRoot(routes);

Above we see the RouterModule.forRoot() function being used to bootstrap our application’s routes. This tells Angular to take our routes const, and configure the routes for our application according to the path and component that we just defined. Additionally, we can make our route configuration easily accessible by exporting it as the default class from this file.

Moving forward, let’s take a look at what we need to do to add our routes to our main application module.

Adding Our Routes to Main App Module
Adding components and RouterModule

At the top of our app.module.ts file we need to import any of the components that we’ve referenced inside of our route configuration in addition to the the actual configuration placed in app.routes.ts. Because we exported our routes as a default class from our routes file, we can set it to any name inside this file. Our example uses the name appRoutes, so our import statements for app.module.ts will look like the following:

// src/app.module.ts
import {
NgModule
}
from '@angular/core';
import {
AppComponent
}
from './app.component';
import {
BrowserModule
}
from '@angular/platform-browser'
import {
HomeComponent
}
from './home.component';
import {
AboutComponent
}
from './about.component';
import {
ContactComponent
}
from './contact.component';
import appRoutes from './app.routes';
Modifying AppModule
Adding Components to declarations

Once everything has been imported, we need to make our application aware of each component that we are routing to. To do this, we need to add the names of each component to our modules declarations property. If we forget to do so, our application will not have the ability to load our components, thus making this process imperative. When our components have been added, our main AppModule‘s declarations property should replicate the code below.

// src/app.module.ts
@
NgModule({
declarations: [
AppComponent,
HomeComponent,
AboutComponent,
ContactComponent
],
imports: /** ...*/
Adding Route Configuration to imports

The last thing we need to do is add our appRoutes class to the imports property. As we learned earlier, RouterModule.forRoot() will bootstrap our routes and configure our URLs according to our preferences, however we must add this configuration to our main AppModule in order to use it.

// src/app.module.ts
imports: [
BrowserModule,
appRoutes
],

Once our routes have been imported, our application will finally be able to load our difference components with the help of a few framework-specific directives.

Adding RouteDirectives to AppComponent

By adding the appRoutes class to our application, we are telling Angular 2 give us access to a handful of RouterDirectives for displaying, and navigating our routes. By taking a look at the template properties for our main AppComponent, we see the following Angular 2.0 directives : <router-outlet> and routerLink.

// src/app.component.ts
@
Component({
selector: 'my-app',
template: `
<ul>
<li>
<a routerLink="">Home</a>
</li>
<li>
<a routerLink="/about">About</a>
</li>
<li>
<a routerLink="/contact">Contact</a>
</li>
</ul>
<router-outlet></router-outlet>
`,

routerLink and router-outlet

The first thing we see are the routerLink directives embedded within our <a> tags. In order for our links to work, we can pass it the path values of each component to this directive. Although we will not be discussing them in this article, this is just one of the many ways in which we can bind routes to the routerLink directive. Once embedded, Angular 2.0 will generate hrefs for each one of our <a routerLink="/path"></a> tags, thus allowing us to jump from route to route! Lastly, we see <router-outlet></router-outlet> being used to actually display the templates from each route. As it’s name suggests, this directive provides an outlet for our routes. It is where each component is going to be loaded. As we know, the HomeComponent will be loaded by default and it will show automatically.

Recap

And thus concludes our tutorial on routing applications in Angular 2.0.

Hopefully, by now, you have received a clearer understanding of how all of this works together and can use that knowledge to route your own applications! Thanks for reading!

Finally, don't forget to pay special attention if you're developing commercial Angular apps that contain sensitive logic. You can protect them against code theft, tampering, and reverse engineering by following our guide.

Jscrambler

The leader in client-side Web security. With Jscrambler, JavaScript applications become self-defensive and capable of detecting and blocking client-side attacks like Magecart.

View All Articles

Subscribe to Our Newsletter