Angular 2 [PART-5] Angular Routing

Routing is used for switch between components , so routing is one of the important section in angular 2 , move from one page to another is by using routing , it is simple , in employee app we implement navigation  section in app.component.html 

For implement Routing we need to update app module app.module.ts  .

1) Create Components

Create  Components

here created Home Component (for home page) , and not fount component (for display page not fount message if call URL not exist )


2)Import router module in Ngmodule

first need to import Router

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

imports: [
BrowserModule, FormsModule, HttpModule , RouterModule.forRoot(appRoutes),
],

 

3) create contant


const appRoutes: Routes = [
{path: 'home' , component: HomeComponent },
{path: 'employeelist' ,component:ListemployeeComponent },
{path: 'newemployee' ,component:EmployeeComponent },
{path: '' , redirectTo:'/home', pathMatch:'full'},
{path: '**' ,component:PageNotFountComponent }
];

 

This is the format of set URL for routing

 {path: 'Your redirect URL' , component: 'Your Component Name '}, 

This is for redirect if there is no URL is selected , used when page first load

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

This last one is used for if there is no URL exist then load this component and show corresponding Result

ex: Page not fount

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

4) Add html navbar in main html page here it is app.comonent.html


<ul class="nav nav-tabs">
 <li class="nav-item "><a routerLinkActive="active" routerLink="home" class="nav-link active">Home</a></li>
 <li class="nav-item"><a routerLinkActive="active" routerLink="employeelist" class="nav-link">Employees</a></li>
 </ul>
 <router-outlet></router-outlet> //Display nav tab result here ( Active Tab result )

<br data-mce-bogus="1">

Leave a Reply

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