Route Parameters and Optional Route Parameters

  • index.html
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>RoutingDemo</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
</head>
<body>
  <app-root></app-root>
</body>
</html>

</head>
<body>
  <app-root></app-root>
</body>
</html>
  • app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule, routingComponents } from './app-routing.module';
import { AppComponent } from './app.component';
import { PageNotFoundComponent } from './page-not-found/page-not-found.component';
import { DepartmentDetailComponent } from './department-detail/department-detail.component';

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

  • app.routing.module.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { DeplartmentListComponent } from './deplartment-list/deplartment-list.component';
import { EmployeeListComponent } from './employee-list/employee-list.component';
import { PageNotFoundComponent } from './page-not-found/page-not-found.component';
import { DepartmentDetailComponent } from './department-detail/department-detail.component';


const routes: Routes = [
  {path: '', redirectTo: '/department-list', pathMatch: 'full'},
  {path: 'department-list', component: DeplartmentListComponent},
  {path: 'department-list/:id', component: DepartmentDetailComponent},
  {path: 'employees', component: EmployeeListComponent},
  {path: '**', component: PageNotFoundComponent}
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }
export const routingComponents = [
  DeplartmentListComponent,
  EmployeeListComponent,
  PageNotFoundComponent
];

  • app.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'RoutingDemo';
}

  • app.component.html
<h1>Routing and Navigation</h1>
<nav>
  <a routerLink="/department-list"> Department </a> <a routerLink="/employees"> Employees </a>
</nav>
<router-outlet></router-outlet>
  • page-not-found.component.ts
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-page-not-found',
  template: `
    <h3>Page not found!</h3>
  `,
  styles: []
})
export class PageNotFoundComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }
}
  • employee-list.component.ts
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-employee-list',
  template: `
    <p>
      employee-list works!
    </p>
  `,
  styles: []
})
export class EmployeeListComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }
}
  • deplartment-list.component.ts
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, ParamMap } from '@angular/router';

@Component({
  selector: 'app-deplartment-list',
  template: `
    <h3>Department List</h3>
    <ul class="items">
      <li [class.selected]="isSelected(department)"  (click)="onSelect(department)" *ngFor="let department of departments">
        <span class="badge badge-secondary">{{department.id}}</span>{{department.name}}
      </li>
    </ul>
  `,
  styles: [`
    .items li.selected{
      background-color: #CFD8DC;
      color: white;
    }
  `]
})
export class DeplartmentListComponent implements OnInit {

  departments = [
    {id : 1, name : 'Angular'},
    {id : 2, name : 'Node'},
    {id : 3, name : 'Mongo'},
    {id : 4, name : 'Ruby'},
    {id : 5, name : 'Bootstrap'}
  ];

  public selectedId;

  constructor(private router: Router, private activatedRoute: ActivatedRoute) { }

  ngOnInit() {
    this.activatedRoute.paramMap.subscribe(
      (paramMap: ParamMap) => {
        let id = parseInt(paramMap.get('id'));
        this.selectedId = id;
      }
    );
  }
  onSelect(department){
    //this.router.navigate(['/departments', department.id]);//absolute path
    this.router.navigate([department.id],{relativeTo: this.activatedRoute}) //relative path
  }

  isSelected(department){
    return department.id ===  this.selectedId;
  }
}
  • department-detail.component.ts
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router, ParamMap } from '@angular/router';

@Component({
  selector: 'app-department-detail',
  template: `
    <h3>You selected department with id {{departmentId}}</h3>
    <a (click)="goPrevious()"> Previous </a>
    <a (click)="goNext()"> Next </a>
    <div>
      <button (click)="gotoDepartments()" >Back</button>
    </div>
  `,
  styles: []
})
export class DepartmentDetailComponent implements OnInit {

  public departmentId;

  constructor(private activateRouter: ActivatedRoute, private router: Router) { }

  ngOnInit() {
    //let id = parseInt(this.activateRouter.snapshot.paramMap.get('id'));
    //this.departmentId = id;
    this.activateRouter.paramMap.subscribe(
      (paramMap: ParamMap) => {
        let id = parseInt(paramMap.get('id'));
        this.departmentId = id;
      }
    );
  }
  goPrevious(){
    let previousId = this.departmentId -1;
    this.router.navigate(["/department-list",previousId]);
    //this.router.navigate([previousId],{relativeTo: this.activateRouter}) //relative path
  }

  goNext(){
    let nextId = this.departmentId + 1;
    this.router.navigate(["/department-list",nextId]); //absolute Path
    //this.router.navigate([nextId],{relativeTo: this.activateRouter}) //relative path
  }

  gotoDepartments(){
    let selectedId = this.departmentId ? this.departmentId : null;
    // this.router.navigate(["/departments",{id: selectedId}]);//passing optional parameter id
    this.router.navigate(['../',{id: selectedId}], { relativeTo: this.activateRouter});
  }
}
  • Output :

Leave a Comment