In Angular, the RouterModule is a core module that provides navigation and routing capabilities for single-page applications (SPAs). It allows you to define routes, navigate between different components, and handle parameters, guards, lazy loading, and more. Let’s break it down step by step.
1. Importing RouterModule
You need to import RouterModule
in your application’s module (usually AppModule
) and configure it with your routes.
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouterModule, Routes } from '@angular/router';
import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { AboutComponent } from './about/about.component';
const routes: Routes = [
{ path: '', component: HomeComponent }, // default route
{ path: 'about', component: AboutComponent },
];
@NgModule({
declarations: [AppComponent, HomeComponent, AboutComponent],
imports: [
BrowserModule,
RouterModule.forRoot(routes) // configure router at the root level
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
2. Using RouterOutlet
<router-outlet>
is a directive where Angular inserts the component matched by the current route.
<!-- app.component.html -->
<nav>
<a routerLink="/">Home</a>
<a routerLink="/about">About</a>
</nav>
<router-outlet></router-outlet>
routerLink
is used instead ofhref
for SPA navigation.- The routed component will be displayed inside
<router-outlet>
.
3. Routing Features
a) Route Parameters
const routes: Routes = [
{ path: 'user/:id', component: UserComponent }
];
Access the parameter in the component:
import { ActivatedRoute } from '@angular/router';
constructor(private route: ActivatedRoute) { }
ngOnInit() {
const id = this.route.snapshot.paramMap.get('id');
}
b) Redirects
{ path: '', redirectTo: '/home', pathMatch: 'full' }
c) Wildcard Route (404)
{ path: '**', component: PageNotFoundComponent }
d) Child Routes
const routes: Routes = [
{ path: 'admin', component: AdminComponent, children: [
{ path: 'dashboard', component: DashboardComponent },
{ path: 'users', component: UsersComponent }
]}
];
e) Lazy Loading
{ path: 'products', loadChildren: () => import('./products/products.module').then(m => m.ProductsModule) }
Summary
- RouterModule: Provides routing features.
- Routes array: Define paths and components.
- RouterOutlet: Placeholder for routed components.
- routerLink: Navigation directive.
- Supports parameters, redirects, guards, child routes, lazy loading.