Let’s dive into the world of routing in Single-Page Applications (SPAs) ie., Angular Routing! Lets take a look at basics of defining routes, navigating between components, and leveraging route parameters for dynamic content.
Setting Up Routing #
- Import RouterModule:
- In your main application module (often
AppModule), importRouterModulefrom@angular/router.import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; @NgModule({ // ... imports: [ // ... RouterModule.forRoot(routes) ], // ... }) export class AppModule { }
- Define Routes:
- Create an array of Objects as
Routesspecifying URL paths and their corresponding components.const routes: Routes = [ { path: '', component: HomeComponent }, { path: 'about', component: AboutComponent }, { path: 'products/:id', component: ProductDetailsComponent } // Route with parameter ]; path: Defines the URL pattern (can include static paths and dynamic segments using:).component: The Angular component to display for this route.
- Configure RouterModule:
- Use
RouterModule.forRoot(routes)in yourAppModuleto configure routing for the application.
Navigation #
There are two main ways to navigate between routes in your Angular app:
- Declarative Navigation:
- Use the
routerLinkdirective in your component’s template to create clickable links. - Bind the
routerLinkto the desired route path.<a routerLink="/about">About Us</a>
-
Programmatic Navigation:
- Inject the
Routerservice into your component. - Use the
navigatemethod to navigate to a specific route.
constructor(private router: Router) {} navigateToAbout() { this.router.navigate(['/about']); } - Inject the
Route Parameters #
Route parameters allow you to capture dynamic segments from the URL and use them in your component.
-
Define Route with Parameter:
- Define with custom :Identifier in the path
{ path: 'products/:id', component: ProductDetailsComponent } -
Access Parameter in Component:
-
Inject the
ActivatedRouteservice into your component. -
Use the
paramMapobservable to access the route parameters.constructor(private route: ActivatedRoute) {} productId=''; ngOnInit() { this.activeRoute.params.subscribe((params:Params)=>{ this.productId=params['id']; }); }
Note: This is just a starting point! Angular Routing offers many more features like child routes, lazy loading, and route guards.