Blog

Web technology tidbits

Configure routing in an Angular CLI project

Angular CLI gets projects up and running quickly. If we're building any substantial web application, soon we'll need to add routing for displaying different views. To add routing, follow the steps below after generating an Angular CLI project.

  1. Open a terminal in the root directory of the application and create a dashboard component: ng g component dashboard
  2. Open index.html and ensure there is a <base href="/"> tag at the top of the head section.
  3. In the root directory of the application, run the command: ng g module app-routing
  4. Open app-routing.module.ts and paste the following configuration:
  5. import { NgModule } from '@angular/core';
    import { RouterModule, Routes } from '@angular/router';
    import { DashboardComponent } from '../dashboard/dashboard.component'
    
    const routes: Routes = [
        {
            path: '',
            component: DashboardComponent,
        },
    ];
    
    @NgModule({
        imports: [
            RouterModule.forRoot(routes)
        ],
        exports: [
            RouterModule
        ],
        declarations: []
    })
    export class AppRoutingModule { }
    
    We export the RouterModule to indicate that our module has a dependency on this module.
  6. Open app.module.ts and add the AppRoutingModule to the imports configuration section.
    ...
    import { AppRoutingModule } from './app-routing/app-routing.module';
    ...
    
    @NgModule({
        ...
        imports: [
            BrowserModule,
            FormsModule,
            HttpModule,
            AppRoutingModule,
        ],
        ...
    })
    
    export class AppModule { }
    
  7. In app.component.html, add <router-outlet></router-outlet> in the space where views should appear.
  8. Save all files. The dashboard view is now displayed within the app component.
  9. Now add other routes in app-routing.module.ts.
    ...
    const routes: Routes = [
        {
            path: '/my-new-route',
            component: MyNewRouteComponent,
        },
        {
            path: '',
            component: DashboardComponent,
        },
    ];
    ...