Javascript

Routing your Angular 2 Application

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

We will explore the Angular 2.0 router with a guide about the core concepts behind routing in an Angular 2 application.

To successfully do so, we will build upon the application in part of this three-part series and route to a few additional components that our sample application included.

By the end of this tutorial, we will have explored the core concepts behind routing in Angular 2.0 while also focusing on the best practices to ensure we build the best coding possible! Those who wish to follow along can find the code for this tutorial in this GitHub repository.

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

Note on External Components

By exploring the plnkr, we will see that the application created in the first article in this series has three additional components: HomeComponent, AboutComponent, and ContactComponent.

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, it is time to 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 and other components we wish to route to. Once we are done configuring our routes, we 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';


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 route.

We use this array to encapsulate the configurations 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 ''.

2. AboutComponent

This will load when the URL points to /about.

3. 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: /#/, /#/about, /#/contact.

As we learned before, our HomeComponent has an empty path, which means it will load automatically. This shows how Angular 2 creates nested child routes a breeze, which can be extremely helpful as applications grow bigger.

Exporting routes as the 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 is 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 the 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 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 app routes, 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 module's declaration 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 declaration 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 must 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 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 different 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 to 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. For our links to work, we can pass 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 display the templates from each route.

As its 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.

Conclusion

This concludes our tutorial on routing applications in Angular 2.0. Hopefully, by now, you have a clearer understanding of how it works together and can use that knowledge to route your applications.

Finally, don't forget to pay special attention if you're developing commercial Angular apps with sensitive logic. You can protect your Angular apps against code theft, tampering, and reverse engineering.

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

Must read next

Web Development

New Year’s Resolution: Build an Angular 2 To Do App

We are going to build our To Do app in ES5 but Angular 2 is fully compatible with ES6 and can be transpiled to ES5 through use of Babel or Typescript.

January 7, 2016 | By Jscrambler | 7 min read

Web Development

Getting Started with Angular 2

Angular 2 has been built to be completely decoupled from the DOM, meaning that developers can use the framework to build more than just web applications.

November 10, 2016 | By Thomas Greco | 6 min read

Section Divider