Introduction
Angular enables developers to build dynamic and interactive web applications. One essential feature of web applications is the ability to pass and retrieve data through query parameters in the URL. This functionality is particularly useful when you want to share information between different components or pages of your Angular application. In this blog, we will explore how to work with query parameters in the Angular Router.
What Are Query Parameters?
Query parameters are key-value pairs that you can append to a URL. They are often used to pass data between different parts of a web application or to provide additional information about the requested resource. Query parameters appear in the URL after a question mark (?
) and are separated by ampersands (&
) if there are multiple parameters.
Here’s an example of a URL with query parameters:
https://example.com/search?query=angular&page=1
In this URL:
- query is a query parameter with the value angular.
page
is another query parameter with the value1
.
In Angular, you can use the Angular Router to work with these query parameters, making it easy to read and manipulate them within your application.
Setting Up Your Angular Application
Before we dive into handling query parameters, let’s make sure you have a basic Angular application set up. If you haven’t already, you can create a new Angular application using the Angular CLI with the following command:
ng new query-params-demo
Once your project is set up, navigate to the project directory:
cd query-params-demo
Configuring Routes
To work with query parameters, you need to define routes in your Angular application. Open the app-routing.module.ts
file in your project, and configure your routes like this:
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home.component';
import { SearchComponent } from './search.component';
const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'search', component: SearchComponent },
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule],
})
export class AppRoutingModule {}
In this example, we have two routes: a default route for the home component and a route for the search component. We will use the search
route to demonstrate working with query parameters.
Navigating to a Route with Query Parameters
To navigate to a route with query parameters, you can use Angular’s Router
service. Here’s how you can do it:
1. Import the Router
service in your component:
import { Router } from '@angular/router';
2. Inject the Router
service into your component’s constructor:
constructor(private router: Router) {}
3. Use the router.navigate
method to navigate to the desired route with query parameters. For example, if you want to navigate to the search
route with query parameters, you can do the following:
navigateToSearch() {
this.router.navigate(['/search'], {
queryParams: { query: 'angular', page: 1 },
});
}
In this code, we are using the queryParams
option to specify the query parameters we want to pass to the search
route.
Accessing Query Parameters
Once you have navigated to a route with query parameters, you can access and work with them in the destination component. In our case, it’s the SearchComponent
. Here’s how you can retrieve query parameters in the component:
1. Import the ActivatedRoute
service:
import { ActivatedRoute } from '@angular/router';
2. Inject the ActivatedRoute
service into your component’s constructor:
constructor(private route: ActivatedRoute) {}
3. Use the queryParamMap
observable provided by ActivatedRoute
to access the query parameters:
ngOnInit() {
this.route.queryParamMap.subscribe((queryParams) => {
// Access query parameters here
const query = queryParams.get('query');
const page = queryParams.get('page');
// Do something with the query parameters
console.log('Query:', query);
console.log('Page:', page);
});
}
In this code, we’re subscribing to the queryParamMap
observable to access the query parameters and then logging them to the console. You can perform any further processing or use the query parameters as needed for your application.
Updating Query Parameters
You can also update query parameters programmatically within your component. For example, you might want to change the page
parameter when a user clicks on a pagination button. Here’s how you can update query parameters:
updatePage(newPage: number) {
this.router.navigate([], {
relativeTo: this.route,
queryParams: { page: newPage },
queryParamsHandling: 'merge', // This preserves existing query parameters
});
}
In this code, we use the router.navigate
method with the queryParams
option to update the page
query parameter. The queryParamsHandling
option set to 'merge'
ensure that existing query parameters are preserved.
Conclusion
Query parameters are a powerful way to pass and retrieve data in an Angular application, and they are a common feature in modern web development. With the Angular Router and the techniques outlined in this blog, you can easily work with query parameters in your Angular applications, making your web applications more dynamic and interactive.
Finally, for more such updates and to read more about such topics, please follow our LinkedIn page Frontend Competency