Creating a new router
De Basef
1) First, create a new routing module:
ng generate module app-routing
2) Create a file named `routes.ts` in `app-routing` folder:
import { Routes } from '@angular/router'; import { Component1 } from '../component1/component1.component'; import { Component2 } from '../component1/component1.component'; import { HomeComponent } from '../home/home.component'; export const routes: Routes = [ { path: 'home', component: HomeComponent }, { path: 'component1', component: Component1 }, { path: 'component2', component: Component2 }, { path: '', redirectTo: '/home', pathMatch: 'full' } ];
3) Update the `app-routing.module.ts` with the `forRoot` and `exports` lines:
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { RouterModule, Routes } from '@angular/router'; import { routes } from './routes'; @NgModule({ imports: [ CommonModule, RouterModule.forRoot(routes) ], exports: [ RouterModule ], declarations: [] }) export class AppRoutingModule { }
4) Update the `app.module.ts` to use the `AppRoutingModule` we just created:
. . . import { AppRoutingModule } from './app-routing/app-routing.module'; @NgModule({ . . . imports: [ . . . AppRoutingModule ], . . . }) . . .
5) Use the `router-outlet` in some HTML file. The route changes will be reflected there:
<router-outlet></router-outlet>
6) The last thing to do is use a link to change the route. In any HTML file:
<a routerLink="/home">Home</a><br /> <a routerLink="/component1">Component 1</a><br /> <a routerLink="/component2">Component 2</a><br />