How to Implement Routing in Angular 6 Application

Introduction

In this article, we are going to learn how to configure routing into the Angular 6 Application. Before proceeding further, I would recommend that you will understand how to Create A New Angular 6 Project Using Angular CLI

We will be setting up routing in a separate routing module and then importing that routing module in our route application module.

Create a Component

Let’s go ahead and create two more components into the angular 6 projects and the components are create-employee-component and a list-employers-component.

Let’s use angular CLI to generate these components

First, generate the create employee component and here is the angular CLI command.

generate the component using the angular CLI command.

we don’t want Spec files that are Unitest files to generate so, let’s set spec to false. And we don’t want a dedicated folder to create for the screed employee component then set a flat option to true.

Now let’s generate list employees component as well there we go we have both the components generated.

generate list of component in angular cli

Import Components

The route module app is also updated to import these two components and include them in the declarations array.

route module app in angular 6 project structure
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

// Import the components 
import { AppComponent } from './app.component';
import { CreateEmployeeComponent } from './employee/create-employee.component';
import { ListEmployeesComponent } from './employee/list-employees.component';

@NgModule({
   declarations:[AppComponent,
   CreateEmployeeComponent,
   ListEmployeesComponent
   ],
  imports: [ BrowserModule ],
  providers:[],
  bootstrap: [AppComponent]
})
export class AppModule { }

We have the two components imported and included in the declarations array here and in the Explorer window we have our employee folder and in that we have the required files for these two components create employee and list employees when setting up routing.

style and scripting files in angular 6

The first step is to set base path in our application host page which is usually index.html

index.html file in angular 6 project
<!Doctype html>
 <html lang="eng">
 <head>
 <meta charset="utf-8">
 <title>Angular6Project</title>
 <base href="/">
 <meta name="viewport" content="width=device-width">
 <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
<app-root></app-root>
</body>
</html>

So, let’s take a look at the index.html file. we already have the base path tells the angular router how to compose navigation URLs when we created this new angular 6 project angular CLI has automatically included this base edge ref element to understand the significance of the Space Age stuff element.

Define Routes

Our next step is to create a routing module and define routes. the first obvious question that comes to your mind is why should we create a separate routing module. the two reasons for separation of concerns and maintainability.

If routing is in its own module then it is easier to find and change routing code if required.

So, let’s go ahead and generate the routing module using the angular CLI here is the command.

generate the Routing module using the angular CLI

We want this routing module import into our route application module so let’s set module option to app there we go we have our separate routing module created and the app.module.ts file also updated to include the required import statement and this app-routing.module.ts is also included in the imports array.

// Import the components so they can be referenced in routes
import { AppComponent } from './app.component';
import { CreateEmployeeComponent } from './employee/create-employee.component';
import { ListEmployeesComponent } from './employee/list-employees.component';
import { AppRoutingModule } from './app-routing.module';

@NgModule({
   declarations:[AppComponent,
   CreateEmployeeComponent,
   ListEmployeesComponent
   ],
  imports: [ BrowserModule ,
             AppRoutingModule   
		 ],
  providers:[],
  bootstrap: [AppComponent]
})
export class AppModule { }

Our next step is to define our application routes in the app-routing.module.ts that we have just created.

We need these three routes to let’s create an empty path route when the user navigates to the list route we want to display list employees component.

Similarly, if the path is create then display create employee component.

If we do not include any client-side path in the URL then we want to redirect the user to this default list route. we want to include these three routes in our app routing module.

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

// Import the components so they can be referenced in routes
import { CreateEmployeeComponent } from './employee/create-employee.component';
import { ListEmployeesComponent } from './employee/list-employees.component';

// The last route is the empty path route. This specifies
// the route to redirect to if the client side path is empty.
const appRoutes: Routes = [
  { path: 'list', component: ListEmployeesComponent },
  { path: 'create', component: CreateEmployeeComponent },
  { path: '', redirectTo: '/list', pathMatch: 'full' }
];

// Pass the configured routes to the forRoot() method
// to let the angular router know about our routes
// Export the imported RouterModule so router directives
// are available to the module that imports this AppRoutingModule
@NgModule({
  imports: [ RouterModule.forRoot(appRoutes) ]
  
})
export class AppRoutingModule { }

But before that, we will have to import the router module and this routes type from “angular router“ package so our app routing module file app-routing.module.ts in this file let’s import router module and routes type from angular router package.

Next, let’s include the three routes and we need to tell the angular router about these three routes and the way we do that is by including router module in the imports array and then use it’s for route method and this the method we pass our three routes which are present in this constant approach.

Add Navigation Component

Now our final step is to define a navigation menu in our root component and to that navigation menu we want to tie these routes our navigation menu HTML looks like this app.component.html

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

We are using bootstrap to style the navigation menu.

This HTML we’re using three directors provided by the router module and those three directives are through a link active router link and router outlet.

The list route activates. we want its associated component which is list employees component display but where should that list employees component view template display. well, that is determined by this router outlet directive so the routed component view template display at this location.

Similarly when they create a route is active then it’s associated component create an employee. the component display at this location.

Let’s build and run our project notice we don’t see anything on the page. let’s launch browser developer tools and see what’s going on look at the error message.

“router outlet is not a known element”.

run angular project using angular 6 cli

Let’s export that imported router module in the array there we go the errors are gone and see our expected output as a navigation menu.

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

// Import the components so they can be referenced in routes
import { CreateEmployeeComponent } from './employee/create-employee.component';
import { ListEmployeesComponent } from './employee/list-employees.component';

// The last route is the empty path route. This specifies
// the route to redirect to if the client side path is empty.
const appRoutes: Routes = [
  { path: 'list', component: ListEmployeesComponent },
  { path: 'create', component: CreateEmployeeComponent },
  { path: '', redirectTo: '/list', pathMatch: 'full' }
];

// Pass the configured routes to the forRoot() method
// to let the angular router know about our routes
// Export the imported RouterModule so router directives
// are available to the module that imports this AppRoutingModule
@NgModule({
  imports: [ RouterModule.forRoot(appRoutes) ],
  exports: [ RouterModule ]
})
export class AppRoutingModule { }

Output

At the moment we select the list route so it displayed “list employee works” message similarly when we navigate to the create route we see the message “create employee works”.

angular 6 routing output in angular cli
angular 6 routing list output in angular cli

Thank you for reading this article and I hope you get started your application using Angular 6. and also read more articles related to mechanical

Leave a Reply

Your email address will not be published. Required fields are marked *