Angular Routing

Implementing routing in an Angular application involves many small steps. Angular CLI does a pretty good job in having some of these routing steps implemented out of the box by just using --routing option.

Before we discuss, how we can use Angular CLI to implement routing let's setup routing manually so we understand all the moving parts as far as implementing routing is concerned.

Using the following command, first create a brand new Angular project using the Angular CLI. ng new employeeManagement

We named it employeeManagement. Let's assume we are using this application to manage employees. Out of the box, Angular CLI has created the root component - AppComponent. In addition let's create the components in the table below. The table shows the component name, it's purpose and the routes we are going to use to get to these components.

Component

Purpose

Route

home

This is the home component

/home

employees

This component displays the list of employees

/employees

pageNotFound

This component is used when a user tries to navigate to a route that does not exist

/nonExistingRoute

Let's generate the above components using Angular CLI. Use the following commands to generate the components. Angular CLI not only generates these components, it also imports and registers the components in the root module.

Component

Command

home

ng g c home

employees

ng g c employees

pageNotFound

ng g c pageNotFound

At this point execute the following Angular CLI commandng serve --open

This builds and launches the application and you will see the following page.

Here are the steps to implement routing in AngularStep 1 : Set <base href> in the application host page which is index.html. The <base href> tells the angular router how to compose navigation URLs. This is already done for us by the Angular CLI, when we created this project.

<basehref="/">

Step 2 : Import the RouterModule into the application root module AppModule. The Router Module contains the Router service and Router directives such as (RouterLink, RouterLinkActive, RouterOutlet etc). So for us to be able to implement routing, we first need to import the Router Module in our AppModule. So in app.module.ts make the following 2 changes

// Import RouterModule

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

// Include RouterModule in the
"imports" array of the @NgModule() decorator

@NgModule({

declarations: [...

],

imports: [

BrowserModule,

RouterModule

],

providers: [],

bootstrap: [AppComponent]

})

exportclassAppModule
{ }

Step 3 : Configure the application routes.

To configure routes, we first need to import Routes type from '@angular/router'. If you look at the definition of Routes type, it is actually an array of Route objects. This Routes type is not required for the application to work. However, using it provides us intellisense and compile time checking. For example, mis-spelled properties of the Route object will be reported as errors.

import
{ RouterModule, Routes
} from'@angular/router';

// Each route maps a URL path to a
component

// The 3rd route specifies the route
to redirect to if the path

// is empty. In our case we are
redirecting to /home

// The 4th route (**) is the wildcard
route. This route is used

// if the requested URL doesn't match
any other routes already defined

constappRoutes: Routes
= [

{ path:'home',
component:HomeComponent
},

{ path:'employees',
component:EmployeesComponent
},

{ path:'',
redirectTo:'/home',
pathMatch:'full'
},

{ path:'**',
component:PageNotFoundComponent
}

];

// To let the router know about the
routes configured above,

// pass "appRoutes"
constant to forRoot(appRoutes) method

// We also have forChild() method. We
will discuss the difference

// and when to use one over the other
in our upcoming videos

@NgModule({

declarations:
[...

],

imports:
[

BrowserModule,

RouterModule.forRoot(appRoutes)

],

providers:
[],

bootstrap:
[AppComponent]

})

exportclassAppModule
{ }

Step 4 : Specify where you want the routed component view template to be displayed using the <router-outlet> directive. In our case we want them to be displayed in the root component AppComponent. So in the root component view template i.e in app.component.html, replace all the existing HTML with <router-outlet></router-outlet>

At this point we should have routing working in our application. Build and run the application using the Angular CLI command : ng serve --open

Notice the URL in the browser. We have /home in the URL and we see 'home works'! displayed.

Now in the URL remove '/home', and type '/employees' and press the enter key. Notice the message 'employees works!' is displayed.

Now in the URL remove '/employees', and type '/abc' and press the enter key. '/abc' is not a valid route so the message 'page-not-found works!' is displayed.

Now remove '/abc' from the URL and press the enter key. Notice we are redirected to '/home' (the default route) and 'home works'! is displayed.

Step 5 : Tie the routes to application menu. Routing is working as expected, but we have to manually type the URL in the address bar. Instead let's include links to our home and employees routes. Let's do this in the Root component(AppComponent). Include the following HTML in app.component.html.

The routerLink directive tells the router where to navigate when the user clicks the link.The routerLinkActive directive is used to add the active bootstrap class to the HTML navigation element whose route matches the active route.

<divstyle="padding:5px">

<ulclass="nav
nav-tabs">

<lirouterLinkActive="active">

<arouterLink="home">Home</a>

</li>

<lirouterLinkActive="active">

<arouterLink="employees">Employees</a>

</li>

</ul>

<br/>

<router-outlet></router-outlet>

</div>

We are using Bootstrap nav component to create the menu. We discussed Bootstrap nav component in Part 27 of Bootstrap tutorial. To install bootstrap execute the following npm commandnpm install bootstrap@3 --save

Once Bootstrap is installed, open .angular-cli.json file and specify the path to the Bootstrap stylesheet in the styles property as shown below.

"styles":
[

"../node_modules/bootstrap/dist/css/bootstrap.min.css",

"styles.css"]

At this point build and run the application using the following Angular CLI command. Routing should be working as expected.ng serve --open

The following are the directives provided by the RouterModule

routerLinkTells the router where to navigate when the user clicks the navigation link

routerLinkActive

When a route is active the routerLinkActive directive adds the active CSS class. When a route becomes inactive, the routerLinkActive directive removes the active CSS class.

The routerLinkActive directive can be applied on the link element itself or it's parent. In this example, for the active route styling to work correctly, routerLinkActive directive must be applied on the <li> element and not the <a> element.

router-outletSpecifies the location at which the routed component view template should be displayed

At the moment routing is implemented in the root module - AppModule. However, for separation of concerns and maintainability, it is better to implement routing in a separate Routing module and then import that routing module in the AppModule. In a later video, we will discuss how to move routing into it's own routing module.

As we have seen throughout this video, there are many moving parts that we have to remember, to implement routing correctly in an angular application. In our next video, we will discuss, the routing workflow and how routing actually works in Angular, by connecting all these little moving parts.