Unlocking Dynamic Navigation: A Guide to routerLink and Query Parameters in Angular
Query parameters, also known as URL parameters, are used to send optional data along with a route in Angular applications. They appear after the question mark (?
) in the URL and are formatted as key-value pairs separated by ampersands (&
).
Passing Query Parameters with routerLink
The routerLink
directive in Angular templates is used to create links that navigate to different parts of your application. To pass query parameters with routerLink
, you can leverage the queryParams
property binding:
<a [routerLink]="['/products', { sort: 'price' }]">Sort by Price</a>
In this example:
['/products']
: This is the route path you want to navigate to (in this case, theProductsComponent
).{ sort: 'price' }
: This is an object defining the query parametersort
with the value'price'
.
Accessing Query Parameters in the Target Component
Once you've navigated to the target route using routerLink
, you can access the passed query parameters within the target component using the ActivatedRoute
service:
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-products',
templateUrl: './products.component.html',
styleUrls: ['./products.component.css']
})
export class ProductsComponent implements OnInit {
sortParam: string;
constructor(private activatedRoute: ActivatedRoute) {}
ngOnInit() {
this.activatedRoute.queryParams.subscribe(params => {
this.sortParam = params['sort'];
// Use the sortParam value to filter or sort products based on the query parameter
});
}
}
Here's a breakdown of the code:
- We import
ActivatedRoute
from@angular/router
. - In
ngOnInit
, we subscribe to thequeryParams
observable of theActivatedRoute
service. - Inside the subscription callback, we access the query parameter value using
params['sort']
. - You can then use the
sortParam
value to filter or sort products in your component logic.
Additional Considerations:
- You can pass multiple query parameters by adding more key-value pairs to the object within
queryParams
. - For dynamic values in
queryParams
, use property binding with component variables (e.g.,[queryParams]="{ sort: mySortVariable }"
). - Remember to handle potential scenarios where the query parameter might be absent (e.g., using default values).
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-products-list',
templateUrl: './products-list.component.html',
styleUrls: ['./products-list.component.css']
})
export class ProductsListComponent implements OnInit {
selectedCategory: string; // Example category variable
constructor() { }
ngOnInit() { }
onCategoryChange(category: string) {
this.selectedCategory = category;
}
}
<div>
<select [(ngModel)]="selectedCategory" (change)="onCategoryChange($event.target.value)">
<option value="">All Categories</option>
<option value="electronics">Electronics</option>
<option value="clothing">Clothing</option>
</select>
<a [routerLink]="['/products', { category: selectedCategory }]">View Products</a>
</div>
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-products',
templateUrl: './products.component.html',
styleUrls: ['./products.component.css']
})
export class ProductsComponent implements OnInit {
category: string;
products: any[] = [ // Replace with your product data
{ category: 'electronics', name: 'Laptop' },
{ category: 'electronics', name: 'Phone' },
{ category: 'clothing', name: 'Shirt' },
{ category: 'clothing', name: 'Jeans' },
];
constructor(private activatedRoute: ActivatedRoute) { }
ngOnInit() {
this.activatedRoute.queryParams.subscribe(params => {
this.category = params['category'];
// Filter products based on category if available
this.products = this.products.filter(product => product.category === this.category || !this.category); // Filter or sort as needed
});
}
}
<h2>Products</h2>
<ul>
<li *ngFor="let product of products">{{ product.name }}</li>
</ul>
Explanation:
-
Component 1:
- The
ProductsListComponent
has aselectedCategory
variable to store the user's chosen category. - The
<select>
element allows users to choose a category. - The
onCategoryChange
function updates theselectedCategory
when the selection changes. - The
routerLink
in the<a>
tag dynamically passes theselectedCategory
as a query parameter to theProductsComponent
.
- The
-
- The
ProductsComponent
injects theActivatedRoute
service. - In
ngOnInit
, it subscribes to thequeryParams
observable. - Inside the subscription, it retrieves the
category
query parameter and assigns it to thecategory
variable. - The product list is filtered based on the
category
(or shown entirely if no category is selected).
- The
Instead of relying on user interaction with a link, you can programmatically navigate using the router.navigate
method from the Router
service:
import { Component } from '@angular/core';
import { Router } from '@angular/router';
@Component({
selector: 'app-my-component',
templateUrl: './my-component.html',
styleUrls: ['./my-component.css']
})
export class MyComponent {
constructor(private router: Router) {}
navigateToProducts(category: string) {
this.router.navigate(['/products'], { queryParams: { category } });
}
}
In this approach, you call navigateToProducts
with the desired category, which then uses router.navigate
to navigate to the /products
route with the category
query parameter.
Using URLSearchParams (More Complex Data):
If you need to pass more complex data structures like objects or arrays as query parameters, you can use URLSearchParams
:
import { Component } from '@angular/core';
import { Router } from '@angular/router';
@Component({
selector: 'app-my-component',
templateUrl: './my-component.html',
styleUrls: ['./my-component.css']
})
export class MyComponent {
constructor(private router: Router) {}
navigateToProducts(filters: any) {
const params = new URLSearchParams();
params.set('filters', JSON.stringify(filters));
this.router.navigate(['/products'], { queryParams: params });
}
}
Here, you create a URLSearchParams
object, set a key-value pair with the filters data stringified as JSON, and then use it with router.navigate
.
State Management (For Complex Application State):
For complex applications with intricate state management, consider using a state management library like NgRx or NgXS. These libraries allow you to store and share application state across components, which can be an alternative to using query parameters for certain scenarios.
Choosing the Right Method:
The best method depends on your specific use case:
routerLink
withqueryParams
: Ideal for simple, user-driven navigation with basic query parameters.router.navigate
: Useful for programmatic navigation with query parameters triggered by code.URLSearchParams
: Suitable for passing more complex data structures as query parameters.- State Management: Consider this for intricate application state that goes beyond simple query parameters.
angular angular2-routing