HI WELCOME TO SIRIS

Angular Routing

Leave a Comment

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.
ComponentPurposeRoute
homeThis is the home component/home
employeesThis component displays the list of employees/employees
pageNotFoundThis 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.
ComponentCommand
homeng g c home
employeesng g c employees
pageNotFoundng g c pageNotFound

At this point execute the following Angular CLI command
ng serve --open

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

Here are the steps to implement routing in Angular
Step 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.

<base href="/">

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]
})
export class AppModule { }

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 { RouterModuleRoutes } 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
const appRoutesRoutes = [
  { 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]
})
export class AppModule { }

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.

<div style="padding:5px">
    <ul class="nav nav-tabs">
        <li routerLinkActive="active">
            <a routerLink="home">Home</a>
        </li>
        <li routerLinkActive="active">
            <a routerLink="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 command
npm 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

routerLink
Tells 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-outlet
Specifies 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.

0 comments:

Post a Comment

Note: only a member of this blog may post a comment.