fbpx Skip to content

Aquent | DEV6

Angular 2: Component Router. Part 1 – Static URLs

Written by: James McGeachie

Please Note: This post was written based on Angular 2 Release Candidate 4. With Release Candidate 5, we’d like to point out the following changes: 

  • You no longer need to import ‘ROUTER_DIRECTIVES’ to use routerLink & routerLinkActive in a component.
  • You no longer need the property binding syntax for routerLink (e.g.’ [routerLink]’ becomes ‘routerLink’).
  • You no longer need to specify the directives array on a component (i.e. you can remove directives: [ROUTER_DIRECTIVES].
  • The module names for router configuration have changed.
  • Modularity and the bootstrapping process has changed.

Please see Part 2 for more details.


Allowing users to navigate to different states of your application is a fundamental aspect of web development. In modern applications we achieve this through the use of a router. For Angular 2, community input has been integral to shaping its routing solution, which has been through multiple iterations. The latest iteration is known as the ‘Component Router’.

So, how does routing work this time around? Let’s go through the basics. In the first part of this topic, we’ll focus on simply navigating between static URLs.

The Base Element.

Our first new requirement is to set the base HREF of our app. This is the base URL to use for all relative URLs. The requirement stems from the fact the Component Router uses the browser’s ‘history.pushState’. If the ‘app’ folder is our project root, as is a common practice, we should include this line within the <head> tags of the index.html file.

<base href=“/">

Navigation

To illustrate the router, let’s imagine a small application that does the following:

  • Displays a home page with a navigation bar
  • Allows us to navigate to a vehicles page that displays a list of vehicles.
  • Allows us to navigate back to the home page from the vehicles page.

In Angular 2, we can envision this with the following components: a parent app component, a home component and a vehicles component. 

Let’s have a look at routing within this setup. Our example code is written in TypeScript.

App Component

import { ROUTER_DIRECTIVES } from '@angular/router';

 

@Component({

  selector: ‘vehicles-app',

  template: `

    <nav>

        <a [routerLink]=“[‘/home’]” routerLinkActive=“active”>Home</a>

        <a [routerLink]="['/vehicles']" routerLinkActive=“active”>Vehicles</a>

    </nav>

    <router-outlet></router-outlet>

  `,

  directives: [ROUTER_DIRECTIVES]

})

For this app component, notice we import the ‘ROUTER_DIRECTIVES’ constant from the Angular library. The router is not needed in all apps, so it must be imported if needed. This also gives you the option to use a third party routing solution. Importing this gives us access to the ‘routerLink’, ‘routerLinkActive’ and ‘<router-outlet>’ directives that you see here.

In the template string we have a <nav> tag with a link to ‘/home’ and a link to ‘/vehicles’. Below this we have the <router-outlet> directive. This shows how we implement simple navigation between pages with static URLs.

By clicking the <a> tag, we populate the <router-outlet> with the component associated with that path. So clicking the link for ‘vehicles’ loads in the vehicles component. By adding more <a> tags with other target paths we can navigate to more states.

So, how do we configure our routes so that pointing to ‘/vehicles’ actually populates the outlet with the correct vehicles component? Let’s look at configuring the router.

Router Configuration

import { provideRouter, RouterConfig }  from '@angular/router';

import { VehiclesComponent } from './vehicles.component';

import { HomeComponent } from ‘./home.component’;

 

const routes: RouterConfig = [

    {

      path: 'vehicles',

      component: VehiclesComponent

    },

    {

      path: ‘home’,

      component: HomeComponent

    }

];

 

export const appRouterProviders = [

  provideRouter(routes)

];

In our router configuration file we import all components for which we require routing, as well as the provideRouter function and RouterConfig class. In this post we won’t cover creating the components themselves, so imagine you have these 2 component files already available.

We create a constant called “routes” using the config class as a type. This is an array of objects, each with 2 properties – path and component. This is how the ‘vehicles’ path is linked to loading the ‘VehiclesComponent’. At the end of this file, we export the appRouterProviders array and within that we call provideRouter and pass our routes array as an argument.

Bootstrap the App

Now that we have our router providers, we need to handle this when we bootstrap the app.

import { AppComponent } from './app.component';

import { appRouterProviders } from './app.routes';

 

bootstrap(AppComponent, [

  appRouterProviders

]);

We call the bootstrap function for our AppComponent and pass the appRouterProviders into the providers array. Our app will now be configured to use all the routes we’ve specified in the router config array. When we serve our app, the navigation bar will now allow routing between the home component and vehicles component.

Next Steps

With these basics we now can configure our app to navigate between any number of static URLs. However, what happens when we need to navigate to a dynamic URL, for example: when a user chooses a specific vehicle?

We’ll answer this question in the upcoming second part, so be sure to check back for the latest updates!

Sign up for our Angular Course

Learn the most recent version and start building your own Angular apps

view course details