How to Add Routing to an Existing Angular Project

What to do if I forgot to add routing when I create new angular app? 



Routing is an option that is available when we initially create an Angular app using the Angular CLI's ng new command. Sometimes we say no to adding routing because we aren't sure if we want to yet. But what if we ultimately decide to add routing? There isn't a separate CLI tool that allows you to configure the routing. I'll demonstrate how to manually add routing to your Angular application in this tutorial.

How To Do

First look at my folder structure



1.  
in app.module.ts, import two things from Angular's router

import { RouterModule, Routes } from '@angular/router';


2. Then, create an array that will hold the route definitions 
const routes: Routes = [];

3. Then in NgModule , Add the router module to imports
@NgModule({
  declarations: [
    AppComponent,
    SearchComponent
  ],
  imports: [
    BrowserModule, RouterModule.forRoot(routes)
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

4The final step in this process is to include a method for the routes to be shown. We can include it in the app component as a router outlet.
<router-outlet></router-outlet>

Test Routing

Let's add our first route to see whether this works. I'll start by creating a new component.
Let's add our first route to see whether this works.
 I'll start by creating a new component:

ng g c search


Then we should add new route for the search component
const routes: Routes = [
  { path: 'search', component: SearchComponent },
  { path: '', redirectTo: '/search', pathMatch: 'full' },
];

Here I will show you the app.module.ts here.
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { RouterModule, Routes } from '@angular/router';
import { SearchComponent } from './search/search.component';
const routes: Routes = [
  { path: 'search', component: SearchComponent },
  { path: '', redirectTo: '/search', pathMatch: 'full' },
];
@NgModule({
  declarations: [
    AppComponent,
    SearchComponent
  ],
  imports: [
    BrowserModule, RouterModule.forRoot(routes)
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
Now run ng serve and see the search route in the browser!