This site runs best with JavaScript enabled.

How to Add Routing to an Existing Angular Project

First Published: May 29th, 2020


When we first create an Angular app with the Angular CLI using ng new, it gives us an option to add routing. Sometimes we don't know whether we want to add routing yet, so we say no. What do we do, though, if we decide to add routing later? There's no separate CLI command to set up the routing for you. In this lesson, I'll show you how to manually add routing to your Angular application.

If you wanted to keep your routes in a separate module, you could do that by creating an app-routing module by using this Angular CLI command:

1ng generate module app-routing --flat --module=app

The flat option will prevent the module from being in its folder and the module option will be sure to import the new module into the AppModule.

I actually don't like this approach. I don't like to keep my routes in a separate routing module; I'd prefer to keep my routes in the same module in which they apply.

To do this, in app.module.ts, I'll first import two things from Angular's router:

1// src/app/app.module.ts
2import { RouterModule, Routes } from '@angular/router'

Then, I need to create an array that will eventually hold my route definitions:

1// src/app/app.module.ts
2const routes: Routes = []

Finally, in my NgModule decorator, I need to add the router module to my imports:

1// src/app/app.module.ts
2@NgModule({
3 imports: [BrowserModule, RouterModule.forRoot(routes)],
4 declarations: [AppComponent, HomeComponent],
5 bootstrap: [AppComponent],
6})
7export class AppModule {}

The last thing we need to do here is add a way for the routes to display. This is called a router outlet and we can add it to the app component:

1// src/app/app.component.ts
2<router-outlet></router-outlet>

To test this is working, let's add our first route. First, I'll generate a new component:

1ng g c home

Then I'll add a new route for the home component and a fallback route in case there's no path to match:

1const routes: Routes = [
2 { path: 'home', component: HomeComponent },
3 { path: '', redirectTo: '/home', pathMatch: 'full' },
4]

You should be able to run ng serve and see the home route in the browser!

Here's the finished code for this video:

You can check out the rest of my egghead Angular Basics playlist for free and sign up for my newsletter below to get my latest coding and career tips sent straight to your inbox.


← Back to writing
Share article

I send emails about getting better at coding and life.

I'm on a path to become a better human and developer and I want to bring as many friends with me as possible. Want to join me? Sign up below. 👇



Sam Julien © 2020