RouterModule provides Angular routing functionality and the routerLink directive. Import it into a feature module when templates need declarative navigation. section 24.2.5 section 6.3.3
Use RouterModule in two closely related ways:
- Import RouterModule directly to enable routerLink attributes that navigate to configured URLs such as /cart, /form/edit, or /. section 24.2.5 section 6.3.3
- Use RouterModule.forChild with route definitions when a feature module owns its URLs and components, including lazy-loaded administration features. section 7.1.1
- Keep routing configuration inside a dynamically loaded module so the module remains self-contained and declares the URLs and components it supports. section 7.1.1
Feature-module routing
Define child routes and include the resulting routing configuration in imports: let routing = RouterModule.forChild([{ path: "auth", component: AuthComponent }, { path: "main", component: AdminComponent }, { path: "**", redirectTo: "auth" }]); @NgModule({ imports: [CommonModule, FormsModule, routing] }) export class AdminModule { } section 7.1.1
Template navigation
Apply routerLink to a button or anchor: <button routerLink="/cart">Cart</button>. Angular navigates to the configured URL when the element is activated; the feature module must import RouterModule. section 6.3.3 section 24.2.5
Listing 7.5. The contents of the admin.module.ts file in the src/app/admin folder
import { NgModule } from "@angular/core";
import { CommonModule } from "@angular/common";
import { FormsModule } from "@angular/forms";
import { RouterModule } from "@angular/router";
import { AuthComponent } from "./auth.component";
import { AdminComponent } from "./admin.component";
let routing = RouterModule.forChild([
{ path: "auth", component: AuthComponent },
{ path: "main", component: AdminComponent },
{ path: "**", redirectTo: "auth" }
]);
@NgModule({
imports: [CommonModule, FormsModule, routing],
declarations: [AuthComponent, AdminComponent]
})
export class AdminModule { }
Browse a complete AdminModule definition showing RouterModule.forChild, route declarations, imports, and component declarations together. section 7.1.1
