Add routing to an Angular CLI project

After creating the project with Angular CLI, complete the following steps to add routing to the project.

  1. Ensure that index.html contains <base href="/"> in the <head> section
  2. Navigate to the projects root folder in a terminal
  3. Generate a module for routing by running ng generate module app-routing
  4. Replace the content of the file app-routing/app-routing.module.ts with
    import { NgModule } from '@angular/core';
    import { RouterModule, Routes } from '@angular/router';
    import { DashComponent } from '../dash/dash.component';
    
    const routes: Routes = [
      {
        path: '',
        redirectTo: 'dash',
        pathMatch: 'full'
      },
      {
        path: 'dash',
        component: DashComponent
      }
    ];
    
    @NgModule({
      imports: [RouterModule.forRoot(routes)],
      exports: [RouterModule],
      declarations: []
    })
    export class AppRoutingModule {}
  5. Update the file app.module.ts so that it contains the following
    ...
    import { AppRoutingModule } from './app-routing/app-routing.module';
    ...
    @NgModule({
      ...
      imports: [..., AppRoutingModule],
      ...
    })
    export class AppModule {}
  6. Generate a component to be used for the default route by running ng generate component dash
  7. Add <router-outlet></router-outlet> to app.component.html in order to display the content of the routes

Leave a Reply

  • Your email address will not be published.
  • Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: