Angular 4 routing tutorial for beginners

Brijpal Sharma
angularjs angular   Publish on:-July 10th, 2018 , Category:- Web Development

We learn in this article how to work AngularCLI routing and how to create a routing based AngularCLI app

To Start this article first we are going to create a fresh angular project by command, Angular CLI(Command line interface) make easier and fast to work with angular CLI project. To create a new Angular project use this command.

ng new routing

Here my project name is "routing". after successfully create this app we are going to create some components.


Create Components in angular CLI


I am going to create some components home, employees and pageNotFound. To Create new components use this Command line.

ng generate component home


ng g c home


Step 1:


 Set "<basehref="/">" in index.php

 <base href="/">


Step 2:

Best Practice for Routes Creates a new separate module by CLI command.

ng generate module app-routing --flat --module=app

The created file looks like this.

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

  imports: [
  declarations: []
export class AppRoutingModule { }


Import the RouteModule into the src/app/app-routing.module.ts page. 

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

'@angular/router'  is a route Package. Now define our routes to define our route creating a const "appRoutes", we know Route is an array and here Four Array object.

const appRoutes:Routes= [
 {path: 'home',component:HomeComponent},
 {path: 'employees',component:EmployeesComponent},
 {path: '' ,redirectTo:'/home',pathMatch:'fill'},
 {path: '**',component:PageNotFoundComponent}

Now let's understand the purpose of each of this object. First When the user calls the path something like "//localhost:4200/home" so this path in the URL match with the first line of Routes.

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

So, in this case, we want to display "HomeComponent" to view.

The fourth Route is special route when the user request for unlisted routes in this above routes "PageNotFoundComponent" component will call.

Next thing to do that let's angular know that where routes are defined. So make a forRoot method for imports

 imports: [


Step 3: 


Specify where you want the route component view template to be displayed using the <router-outlet> directive. Edit app.component.html 


Now test your application manually in the browser.

Ok Great, now Test for employees and see what happens.




Brijpal Sharma

Hello, My Name is Brijpal Sharma. I am a Web Developer, Professional Blogger and Digital Marketer from India. I am the founder of Codermen. I started this blog to help web developers & bloggers by providing easy and best tutorials, articles and offers for web developers and bloggers...


You must be logged in to post a comment.