We are providing online training of realtime Live project on Asp.Net MVC with Angular and Web API. For more information click here. If you have any query then drop the messase in CONTACT FORM

Tuesday, May 29, 2018

Routes concept with example in Angular 2

In this article, we will see the Routes concept in angular 2 and we will see an example.

Introduction 

Routing allows us to express some aspects of the application's state in the URL. Unlike with server-side front-end solutions, this is optional - we can build the full application without ever changing the URL. Adding routing, however, allows the user to go straight into certain aspects of the application. This is very convenient as it can keep your application linkable and bookmarkable and allow users to share links with others. And also we can create Single Page Applications using Angular 
+

Routing allows you to:
  • Maintain the state of the application
  • Implement modular applications
  • Implement the application based on the roles (certain roles have access to certain URLs)

Attributes of Routes in angular 2

  • path - URL to be shown in the browser when the application is on the specific route
  • component - component to be rendered when the application is on the specific route
  • redirectTo - redirect route if needed; each route can have either component or redirect attribute defined in the route 
  • pathMatch - the optional property that defaults to 'prefix'; determines whether to match full URLs or just the beginning. When defining a route with empty path string set pathMatch to 'full', otherwise it will match all paths.
  • children - an array of route definitions objects representing the child routes of this route
  • outlet: It is the name of the outlet the component should be placed into.
  • canActive: It is an array of DI tokens used to look up CanActivate handlers. 

export const routes: Routes = [
    { path: '', redirectTo: 'home', pathMatch: 'full' },
    { path: 'home', component: HomeComponent }

];

Now we will start our real time example

First, we need to configure of in the visual studio. So already I explained how to install typescript and configuration of reference file of angular js in Visual Studio 
For this, you can go this link

In this example, we will take some details of Employee, Customer, User, Education, Address to perform our route example or you can take as your requirement.

So now first right click of app folder and add a Typescript file and give the name app.routes.ts and write below code.


import { RoutesRouterModule } from '@angular/router';
import { HomeComponent } from './app.component.home';
import { UserComponent } from './app.component.user';
import { EmployeeComponent } from './app.component.employee';
import { EducationComponent } from './app.component.education';
import { AddressComponent } from './app.component.address';
import { CustomerComponent } from './app.component.customer';

export const routesRoutes = [
    { path: ''redirectTo: 'home'pathMatch: 'full' },
    { path: 'home'component: HomeComponent },
    { path: 'Customer'component: CustomerComponent },
    { path: 'User'component: UserComponent },
    { path: 'Employee'component: EmployeeComponent },
    { path: 'Address'component: AddressComponent },
    { path: 'Education'component: EducationComponent }

];

 export const appRoutingProvidersany[] = [ 
]; 

export const routing = RouterModule.forRoot(routes);  

Again right click of app folder and add a Typescript file and give the name app.component.user.ts and write below code.



import { ComponentOnInitViewChild } from '@angular/core';

@Component({
    moduleId: module.id,
    selector: 'customer',
    templateUrl: 'app.component.user.html'
})

export class UserComponent implements OnInit {

    private userDetailsArray<any> = [];

    constructor() {
        this.userDetails = [
            { UserId: 'User001'UserName: 'Mithilesh'MobileNo: '9238493410'EmailId: 'mithilesh@gmail.com' },
            { UserId: 'User002'UserName: 'Sam'MobileNo: '9234493410'EmailId: 'Sam@gmail.com' },
            { UserId: 'User003'UserName: 'Sohan'MobileNo: '9238423410'EmailId: 'Sohan@gmail.com' },
            { UserId: 'User004'UserName: 'Mohan'MobileNo: '6354354344'EmailId: 'Mohan@gmail.com' },
            { UserId: 'User005'UserName: 'Surya'MobileNo: '9223493410'EmailId: 'Surya@gmail.com' }
        ];
    }

    ngOnInit(): void {
    }

}  


Again right click of the app folder and add an Html file and give the name app.component.user.html and write the below code.

<div class="panel-body">
    <table class="table table-striped table-bordered">
        <thead>
            <tr class="btn-danger">
                <th>User Id</th>
                <th>User Name</th>
                <th>Mobile Number</th>
                <th>EmailId</th>
            </tr>
        </thead>
        <tbody>
            <tr *ngFor="let item of userDetails">
                <td>{{item.UserId}}</td>
                <td>{{item.UserName}}</td>
                <td>{{item.MobileNo}}</td>
                <td>{{item.EmailId}}</td>
            </tr>
        </tbody>
    </table>
</div>       

Again right click of app folder and add a TypeScript file and give the name app.component.employee.ts and write below code.

@Component({
  moduleId: module.id,
  selector: 'employee',
  templateUrl: 'app.component.employee.html'
})

export class EmployeeComponent implements OnInit {

  private employeeDetailsArray<any> = [];

  constructor() {
      this.employeeDetails = [
          { EmpId: 'Emp001'EmpName: 'Mithilesh'MobileNo: '9238493410'Location: 'Hyderabad' },
          { EmpId: 'Emp002'EmpName: 'Sam'MobileNo: '9234493410'Location: 'Banglore' },
          { EmpId: 'Emp003'EmpName: 'David'MobileNo: '98732434'Location: 'Delhi' },
          { EmpId: 'Emp004'EmpName: 'Jacki'MobileNo: '6354354344'Location: 'Mumbai' },
          { EmpId: 'Emp005'EmpName: 'Sachin'MobileNo: '9343393410'Location: 'Pune' }
      ];
  }

  ngOnInit(): void {
  }

}  
Again right click of app folder and add a Html file and give the name app.component.employee.html and write below code.

<div class="panel-body">
    <table class="table table-striped table-bordered">
        <thead>
            <tr class="btn-danger">
                <th>Eployee Id</th>
                <th>Employee Name</th>
                <th>Mobile Number</th>
                <th>Location</th>
            </tr>
        </thead>
        <tbody>
            <tr *ngFor="let item of employeeDetails">
                <td>{{item.EmpId}}</td>
                <td>{{item.EmpName}}</td>
                <td>{{item.MobileNo}}</td>
                <td>{{item.Location}}</td>
            </tr>
        </tbody>
    </table>

</div>    

Again right click of app folder and add a Typescript file and give the name app.component.education.ts and write below code.

import { ComponentOnInitViewChild } from '@angular/core';

@Component({
    moduleId: module.id,
    selector: 'education',
    templateUrl: 'app.component.education.html'
})

export class EducationComponent implements OnInit {

    private educationDetailsArray<any> = [];

    constructor() {
        this.educationDetails = [
            { EducationId: 'Edu_01'Qualification: 'MCA'University: 'BPUT'Location: 'Odisa' },
            { EducationId: 'Edu_02'Qualification: 'B. Tech'University: 'Amity'Location: 'Noida' },
            { EducationId: 'Edu_03'Qualification: 'Msc IT'University: 'Kuvempu'Location: 'banglore' },
            { EducationId: 'Edu_04'Qualification: 'PG'University: 'D U'Location: 'Delhi' },
        ];
    }

    ngOnInit(): void {
    }

}  


Again right click of the app folder and add an Html file and give the name app.component.education.html and write the below code.

 <div class="panel-body">
    <table class="table table-striped table-bordered">
        <thead>
            <tr class="btn-danger">
                <th>Education Id</th>
                <th>Qualification</th>
                <th>University</th>
                <th>Location</th>
            </tr>
        </thead>
        <tbody>
            <tr *ngFor="let item of educationDetails">
                <td>{{item.EducationId}}</td>
                <td>{{item.Qualification}}</td>
                <td>{{item.University}}</td>
                <td>{{item.Location}}</td>
            </tr>
        </tbody>
    </table>

</div>   

Again right click of app folder and add a Typescript file and give the name app.component.customer.ts  and write below code.

import { ComponentOnInitViewChild } from '@angular/core';

@Component({
    moduleId: module.id,
    selector: 'customer',
    templateUrl: 'app.component.customer.html'
})

export class CustomerComponent implements OnInit {

    private customerDetailsArray<any> = [];

    constructor() {
        this.customerDetails = [
            { CustomerId: 'Cust001'FirstName: 'Mithilesh'LastName: 'Kumar'MobileNo: '9238493410'PineCode: '823782' },
            { CustomerId: 'Cust002'FirstName: 'Sam'LastName: 'Verma'MobileNo: '9234493410'PineCode: '829782' },
            { CustomerId: 'Cust003'FirstName: 'Rahul'LastName: 'Chadda'MobileNo: '9238423410'PineCode: '823192' },
            { CustomerId: 'Cust004'FirstName: 'Mohan'LastName: 'Kumar'MobileNo: '234343233'PineCode: '813782' },
            { CustomerId: 'Cust005'FirstName: 'Hari'LastName: 'Om'MobileNo: '9223493410'PineCode: '822782' }
        ];
    }

    ngOnInit(): void {
    }

}  


Again right click of the app folder and add an Html file and give the name app.component.customer.html and write the below code.


<div class="panel-body">
    <table class="table table-striped table-bordered">
        <thead>
            <tr class="btn-danger">
                <th>Customer Id</th>
                <th>First Name</th>
                <th>Last Name</th>
                <th>Mobile Number</th>
                <th>PineCode</th>
            </tr>
        </thead>
        <tbody>
            <tr *ngFor="let item of customerDetails">
                <td>{{item.CustomerId}}</td>
                <td>{{item.FirstName}}</td>
                <td>{{item.LastName}}</td>
                <td>{{item.MobileNo}}</td>
                <td>{{item.PineCode}}</td>
            </tr>
        </tbody>
    </table>
</div>     

Again right click of app folder and add a Typescript file and give the name app.component.address.ts and write below code.


import { ComponentOnInitViewChild } from '@angular/core';

@Component({
    moduleId: module.id,
    selector: 'address',
    templateUrl: 'app.component.address.html'
})

export class AddressComponent implements OnInit {

    private addressDetailsArray<any> = [];

    constructor() {
        this.addressDetails = [
            { AddressId: 'Add_01'CountryName: 'India'StateName: 'Telangana'District: 'Hyderabad'PineCode: '50021' },
            { AddressId: 'Add_02'CountryName: 'America'StateName: 'Nework'District: 'Nework'PineCode: '82122' },
            { AddressId: 'Add_03'CountryName: 'India'StateName: 'Maharstra'District: 'Pune'PineCode: '123456' },
            { AddressId: 'Add_04'CountryName: 'India'StateName: 'Dlhi'District: 'New Dlhi'PineCode: '12345' },
            { AddressId: 'Add_05'CountryName: 'India'StateName: 'M P'District: 'Bhopal'PineCode: '63643' },
        ];
    }

    ngOnInit(): void {
    }

}  


Again right click of the app folder and add an Html file and give the name app.component.address.html and write the below code.

<div class="panel-body">
    <table class="table table-striped table-bordered">
        <thead>
            <tr class="btn-danger">
                <th>Address Id</th>
                <th>Country Name</th>
                <th>State Name</th>
                <th>District</th>
                <th>PineCode</th>
            </tr>
        </thead>
        <tbody>
            <tr *ngFor="let item of addressDetails">
                <td>{{item.AddressId}}</td>
                <td>{{item.CountryName}}</td>
                <td>{{item.StateName}}</td>
                <td>{{item.District}}</td>
                <td>{{item.PineCode}}</td>
            </tr>
        </tbody>
    </table>

</div>    

Again right click of app folder and add a Typescript file and give the name app.component.homepage.ts and write below code.

import { ComponentOnInitViewChild } from '@angular/core';

@Component({
    moduleId: module.id,
    selector: 'home-page',
    templateUrl: 'app.component.homepage.html'
})

export class HomePageComponent implements OnInit {

    constructor() {
    }

    ngOnInit(): void {
    }

}  
Again right click of the app folder and add an Html file and give the name app.component.homepage.html and write the below code.
<div class="container">
    <div align="center" class="rowDiv panel panel-primary">
        <h2 class="panel-heading btn-primary">Route Example In Angular 2</h2>
        <table style="width:100%;">
            <tr class="well-sm">
                <td><a routerLink="/home" class="btn-block">Home</a></td>
                <td><a routerLink="/Customer">Customer Details</a></td>
                <td><a routerLink="/User">User Details</a></td>
                <td><a routerLink="/Employee">Employee Details</a></td>
                <td><a routerLink="/Address">Address Details</a></td>
                <td><a routerLink="/Education">Education Details</a></td>
            </tr>
        </table>
    </div>
    <div class="rowDiv navbar-form">
        <router-outlet></router-outlet>
    </div>
</div>
<style>
    td {
        padding: 14px;
        color: white;
    }

</style>

Again right click of app folder and add a Typescript file and give the name app.component.home.ts and write below code.
import { Component, OnInit, ViewChild } from '@angular/core';
@Component({
  moduleId: module.id,
  selector: 'home',
  templateUrl: 'app.component.home.html'
})

export class HomeComponent implements OnInit {

  private messagestring = '';
  constructor() {
      this.message = 'This our home page';
  }

  ngOnInit(): void {
  }
}   


Again right click of the app folder and add an Html file and give the name app.component.home.html and write below code.


<div class="row">
    <div class="panel-body">
        Home Page
        <br />
        <h3 class="panel-heading"><span>{{message}}</span></h3>
        <img src="../../Images/homepage-dsim.jpg" />
    </div>
</div>   

Again right click of app folder and add a Typescript file and give the name app.module.ts and write below code.
import { NgModuleNO_ERRORS_SCHEMA } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from "@angular/forms";

import { routingappRoutingProviders } from './app.routes';
import { HomePageComponent } from './app.component.homepage';
import { HomeComponent } from './app.component.home';
import { UserComponent } from './app.component.user';
import { EmployeeComponent } from './app.component.employee';
import { EducationComponent } from './app.component.education';
import { AddressComponent } from './app.component.address';
import { CustomerComponent } from './app.component.customer';

@NgModule({
    imports: [BrowserModuleFormsModulerouting],
    declarations: [HomePageComponentHomeComponentUserComponentEmployeeComponentEducationComponentAddressComponentCustomerComponent],
    bootstrap: [HomePageComponent],
    schemas: [NO_ERRORS_SCHEMA],
    providers: [appRoutingProviders],
})
export class AppModule { }  

Now modify the directive in index.html page

<body>
    <home-page>Please wait Angular application is loading ...</home-page>
</body>



Output:



No comments: