Support us .Net Basics C# SQL ASP.NET ADO.NET MVC Slides C# Programs Subscribe Buy DVD

Angular routing and navigation

Suggested Videos
Part 1 - Angular project setup | Text | Slides
Part 2 - Reading data in angular | Text | Slides

In this video we will discuss setting up routing in our sample application. Here are the steps.


Step 1 : At the moment, in our application we have only one component (ListEmployeesComponent). Let's create another component. In our upcoming videos we will discuss how to create a new employee. So let's add CreateEmployeeComponent. Use the following Angular CLI command to generate the component.

ng g c employees/createEmployee --spec false --flat true


Step 2 : 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.

<base href="/">

We will discuss the significance of this base href element in detail in our next video.

Step 3 : 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 changes. Notice the changes are commented and self-explanatory.

// 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]
})

export class AppModule { }

Step 4 : 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 /list

// pathMatch property value can be full or prefix. For now we
// will set it to full as we want to do a full match. In our upcoming videos,
// we will discuss the difference between prefix and full in detail.

const appRoutes: Routes = [
  { path: 'list', component: ListEmployeesComponent },
  { path: 'create', component: CreateEmployeeComponent },
  { path: '', redirectTo: '/list', pathMatch: 'full' }
];

// 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]
})

export class AppModule { }

Step 5 : Create the application menu and tie the routes to it. Notice we are using routerLink directive. This directive tells the router where to navigate when the user clicks the link. We are also using router-outlet directive. This directive specifies where you want the routed component view template to be displayed. We want our navigation menu to be always displayed, so the ideal location for it is the root component AppComponent i.e app.component.html file. When the application first loads, it loads the root AppComponent in index.html. So let's place the following HTML in app.component.html file.

<div class="container">
    <nav class="navbar navbar-default">
        <ul class="nav navbar-nav">
            <li>
                <a routerLink="list">List</a>
            </li>
            <li>
                <a routerLink="create">Create</a>
            </li>
        </ul>
    </nav>
    <router-outlet></router-outlet>
</div>

As you can see, in the HTML we have 2 things - Navigation menu and the <router-outlet> directive. The navigation menu is always displayed. Below the navigation menu, we have the <router-outlet> directive. This is the location where the routed component view template is displayed. 

For example, when we click on the "List" link in the navigation menu, the route changes to "/list" and the ListEmployeesComponent view template is displayed at the location where we have the <router-outlet> directive. At this point, if we click on "Create" link, 2 things happen

1. The route changes from "/list" to "/create" 
2. ListEmployeesComponent view template is replaced with CreateEmployeeComponent view template

Also notice, if we navigate to the root of the application i.e if we do not include "/list" or "/create" in the URL, the router automatically redirects us to "/list". This is because of the following empty route we have in our route configuration.

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

We are using Bootstrap navbar component to create the navigation menu. We discussed Bootstrap navbar component in Part 28 of Bootstrap tutorial.

Since we are now routing to ListEmployeesComponent we no longer need it's selector. So remove the selector specified in the @Component decorator of ListEmployeesComponent

At the moment both the menu items, i.e the active and the inactive menu items are styled the same way. As a result we don't know which page the user is on. We will discuss how to address this in our upcoming videos.

In our next video, we will discuss the significance of the <base href="/"> element in index.html page.

angular crud tutorial