After creating the project with Angular CLI, complete the following steps to add routing to the project.
- Ensure that index.html contains
<base href="/">in the<head> section - Navigate to the projects root folder in a terminal
- Generate a module for routing by running
ng generate module app-routing - Replace the content of the file
app-routing/app-routing.module.tswithimport { 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 {} - 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 {} - Generate a component to be used for the default route by running
ng generate component dash - Add
<router-outlet></router-outlet>toapp.component.htmlin order to display the content of the routes