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.
Open a terminal in the root directory of the application and create a dashboard component: ng g component dashboard
Open index.html and ensure there is a <base href="/">
tag at the top of the head
section.
In the root directory of the application, run the command: ng g module app-routing
Open app-routing.module.ts and paste the following configuration:
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.
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 { }
In app.component.html, add <router-outlet></router-outlet>
in the space where views should appear.
Save all files. The dashboard view is now displayed within the app component.
Now add other routes in app-routing.module.ts.
...
const routes: Routes = [
{
path: '/my-new-route',
component: MyNewRouteComponent,
},
{
path: '',
component: DashboardComponent,
},
];
...