Routing via app-routing.module.ts file

1. We need to create a angular project with routing module in it, command below

ng new RoutingDemo --routing

2. We need to add two components into this project with inline template and inline css, command below

ng g c deplartment-list -it -is
ng g c employee-list -it -is 

3. Now modify app-routing.module.ts as below :
Note : we have create a constants named routingComponents in here hence we need not import these components again in app.module.ts, we just need to import the constant in it.

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';

const routes: Routes = [
  {path: 'departments', component: DeplartmentListComponent},
  {path: 'employees', component: EmployeeListComponent}

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

4. Modify app.module.ts as below :
Note : We have imported the constant “routingComponents” from app-routing.module.ts file

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule, routingComponents } from './app-routing.module';
import { AppComponent } from './app.component';

  declarations: [
  imports: [
  providers: [],
  bootstrap: [AppComponent]
export class AppModule { }

5. Modify app.component.html as below :

<h1>Routing and Navigation</h1>
  <a routerLink="/departments"> Department </a> <a routerLink="/employees"> Employees </a>

6. Output looks like below :

Leave a Comment