Angular routing helps navigation across the application from one view to another view. It also allows us to maintain the state, implement modules, and load the modules based on the role of the user. Let’s see in this article how we configure the routing and some basic concepts with it. For this let’s add 3 component in the application Namely Home, Employee and Department our goal is to load the following pages below is the routing table for the configuration,
| Path | URL | Component |
| / | Localhost:4200 | Employee |
| /Employee | Localhost:200/Employee | Employee |
| /Department | Localhost:4200/Department | Department |
Basic Setup
In this let’s see the basic import that we need to do so as to make the routing work in our application. To use the routing module we need to import some package in the application module which can be like this
import {Routes,RouterModule} from '@angular/router';
Route Configuration
Now next step is to map the URL to a component that can be shown on the page which is done by using the Route Configuration which is nothing but the array of the path how we can do this. Let's add new class file and name it as ApplicationRoutes.ts. The code snippet for the same is like below.
- import {Routes} from '@angular/router';
- import { EmployeeComponent } from './employee/employee.component';
- import { DepartmentComponent } from './department/department.component';
- export const routes: Routes = [
- { path: '', component: EmployeeComponent },
- { Path: 'employee', component: EmployeeComponent },
- {Path: 'Department', component: DepartmentComponent }
- ]
There are two main part which are,
- path: It describe the URL this route handle
- component: This is the name of the component we want to display when URL in the Browser matches the Route
- Routes: This is the typescript array of the Routes
Next thing what we need to do is we need to import these routs in the application we can do this by adding lines RouterModule.forRoutes(routes) into the imports section of the Application Module
- import { BrowserModule } from '@angular/platform-browser';
- import { NgModule } from '@angular/core';
- import {RouterModule} from '@angular/router';
- import { AppComponent } from './app.component';
- import { HomeComponentComponent } from './home-component/home-component.component';
- import { EmployeeComponent } from './employee/employee.component';
- import { DepartmentComponent } from './department/department.component';
- import {routes} from './ApplicationRoutes'
- @NgModule({
- declarations: [
- AppComponent,
- HomeComponentComponent,
- EmployeeComponent,
- DepartmentComponent
- ],
- imports: [
- BrowserModule
- ,
- RouterModule.forRoot(routes, {useHash: true})
- ],
- providers: [],
- bootstrap: [AppComponent]
- })
- export class AppModule {
- }


Join the conversation! Your thoughts help the community grow.