Routing in Angular
Angular routing is one of the framework’s core features that enables navigation between components and modules. With Angular’s built-in tools, you can create a seamless user experience without page reloads, giving your application a smooth, SPA-like feel.
Path vs Query Parameters
- Path parameters are part of the URL and are typically used when you want the parameter to be essential to the route. They’re commonly used for unique identifiers like IDs.
const routes: Routes = [
{ path: 'books/:bookID/author/:authorID', component: BookComponent }
];
2. Query parameters, on the other hand, are added to the URL after a ?
and can contain additional information, often for search filters or sorting options.
const routes: Routes = [
{ path: 'product', component: ProductComponent }
];
Now, let's see how we can use path and query parameters for redirecting to different components and modules and accessing the path and query variable from the routes in Angular:
1. Path Parameters in Angular
To pass path parameters, use the routerLink
directive in your HTML template:
<a [routerLink]="['book', bookID, 'author', authorID]">View Book</a>
Or we can use Router
library from Angular:
import { Router } from '@angular/router';
constructor(private router: Router) {}
redirectUsingPath() {
if (this.pathBookSearch && this.pathAuthorSearch) {
this.router.navigate(['home', 'book', this.pathBookSearch, 'author',
} else {
alert('Please enter both a Book ID and Author name.');
}
}
Retrieving Path Parameters
There are two main ways to retrieve path parameters in Angular:
- Snapshot: Great for when the route does not change while the component is active.
this.bookID = this.route.snapshot.paramMap.get('bookID');
- Observable: Use when the route can change dynamically, and you need to listen for updates.
this.route.paramMap.subscribe(params => {
this.bookID = params.get('bookID');
});
2. Query Parameters in Angular
Query parameters are passed using an object with queryParams
:
<a [routerLink]="['product']" [queryParams]="{ search: searchValue }">Search Product</a>
Or we can use Router
library from Angular:
import { Router } from '@angular/router';
constructor(private router: Router)
redirectUsingQuery() {
if (this.querySearch) {
this.router.navigate(['home', 'product'], { queryParams: { search: this.querySearch } });
} else {
alert('Please enter product name.');
}
}
Retrieving Query Parameters
You can retrieve query parameters using the same snapshot and observable techniques:
- Snapshot: Great for when the route does not change while the component is active.
this.searchValue = this.route.snapshot.queryParamMap.get('search');
- Observable: Use when the route can change dynamically, and you need to listen for updates.
this.route.queryParamMap.subscribe(params => {
this.searchValue = params.get('search');
});
Router Outlet
<router-outlet>
is a directive in Angular that serves as a placeholder for loading different components based on the active route. It’s an essential element in Angular’s routing system.
<app-header></app-header>
<router-outlet></router-outlet>
<app-footer></app-footer>
- Angular routing follows a first-match-wins strategy using a depth-first search approach.
- This means Angular checks each route in the configuration tree from top to bottom and left to right, taking the first matching route it finds and ignoring any subsequent matches.
- The routing engine starts from the root and traverses downwards, favoring deeper routes first within each level before moving to the next sibling.
- This way, specific routes are matched before more generic ones, creating predictable navigation behavior.
Router vs ActivatedRoute in Angular
- Router: Primarily used for navigation and controlling routes programmatically.
- ActivatedRoute: Provides access to information about a route, such as parameters, query parameters, and route metadata.
Angular Navigation Lifecycle Events
In Angular, a navigation cycle refers to the events that occur as the router processes and resolves a route change. During this cycle, the Angular Router
emits several events, which can be observed using an observable provided by the Router
service. This allows you to perform actions (like showing a loading spinner) or debug routing.
Here’s a breakdown of the key events in the navigation cycle:
- NavigationStart: This event marks the beginning of a navigation. It fires when Angular starts the process of moving to a new route, signaling that the route change is in progress.
- RoutesRecognized: This event occurs when the router successfully matches the requested URL to a defined route. At this stage, the router has identified which component and data should load for the new route.
- NavigationCancel: This event triggers if the navigation is interrupted, such as when a guard (Route Guards) prevents access to a route or when another route change occurs before navigation completes. It signals that the router has canceled the navigation.
- NavigationEnd: This event fires when the navigation is fully complete, indicating the router has successfully reached the desired route. You can use this event to stop any loading animations since navigation has finished.
These events allow developers to respond to specific points in the navigation lifecycle, such as starting or stopping animations, logging, or handling errors when navigation fails.
I have a GitHub repository where I demonstrate this concept. You can check it out here:
Conclusion
Thank you for reading! I hope this guide helps you in your journey to mastering Angular. If you have any questions or feedback, feel free to leave a comment below.
Happy developing!