In this example we will be redirecting an non existing URL to a page not found page and we will also be writing the logic to redirect a root page of URL i.e “/” to a specific page.
- 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'; const routes: Routes = [ {path: '', redirectTo: '/departments', pathMatch: 'full'}, {path: 'departments', component: DeplartmentListComponent}, {path: 'employees', component: EmployeeListComponent}, {path: '**', component: PageNotFoundComponent} ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { } export const routingComponents = [ DeplartmentListComponent, EmployeeListComponent, PageNotFoundComponent ];
- 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'; @NgModule({ declarations: [ AppComponent, routingComponents, PageNotFoundComponent ], imports: [ BrowserModule, AppRoutingModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
- app.component.html
<h1>Routing and Navigation</h1> <nav> <a routerLink="/departments"> Department </a> <a routerLink="/employees"> Employees </a> </nav> <router-outlet></router-outlet>
- 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'; }
- 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'; @Component({ selector: 'app-deplartment-list', template: ` <p> deplartment-list works! </p> `, styles: [] }) export class DeplartmentListComponent implements OnInit { constructor() { } ngOnInit() { } }
- 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() { } }
