How to use query parameters in Angular
Query parameters enable passing optional data through URLs, perfect for filtering, pagination, and maintaining application state. As the creator of CoreUI with extensive Angular development experience since 2014, I’ve used query parameters extensively in admin dashboards for search filters and table pagination. The most effective approach combines ActivatedRoute for reading and Router for navigation with query parameters. This pattern provides flexible URL-based state management that enhances user experience and enables bookmarkable application states.
Use ActivatedRoute to read query parameters and Router to navigate with them.
import { Component, OnInit } from '@angular/core'
import { ActivatedRoute, Router } from '@angular/router'
@Component({
selector: 'app-product-list',
template: `
<input (input)="search($event)" placeholder="Search products">
<p>Search: {{searchTerm}}</p>
`
})
export class ProductListComponent implements OnInit {
searchTerm: string = ''
constructor(
private route: ActivatedRoute,
private router: Router
) {}
ngOnInit() {
this.route.queryParams.subscribe(params => {
this.searchTerm = params['search'] || ''
})
}
search(event: any) {
this.router.navigate([], {
queryParams: { search: event.target.value },
queryParamsHandling: 'merge'
})
}
}
This code reads the search query parameter on component initialization and updates the search term when query parameters change. The search method navigates to the current route with updated query parameters, maintaining other existing parameters with queryParamsHandling: 'merge'. This creates URLs like /products?search=laptop that users can bookmark and share.
Best Practice Note:
This is the same approach we use in CoreUI data tables for filters and pagination. Always handle missing query parameters with default values to prevent undefined states in your components.



