- Published on
Angular — Query Params (?)
- Authors
- Name
A Visual Representation of Query Params In Angular
Query parameters are key-value pairs added to the end of a URL after a question mark (?
). They are used to pass additional information to a web page in our application. In Angular, query parameters can be accessed and manipulated using the ActivatedRoute
service from the @angular/router
module.
Why use Query Params?
- Using Query Params, We can easily add Searching functionality to our application.
- Query Params also allow filtering things based on some criteria.
- It can be used to sort things.
- They can also be used to restrict users from allowing access to certain pages of your website.
Problem:
Let’s say, we have an e-commerce application. We want users to be able to filter products based on some criteria, e.g., product category, product min and max price etc. Which approach will we use to achieve this?
One simple and easy approach to this problem is the use of query params
.
We can use query parameters to filter products based on those specified Criteria.
Let’s give an example.
// products.component.ts
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 {
products: Product[] = []; // Assume Product interface is defined
filteredProducts: Product[] = [];
constructor(private route: ActivatedRoute) { }
ngOnInit() {
this.route.queryParamMap.subscribe(params => {
const categoryParam = params.get('category');
this.filterByCategory(categoryParam);
});
}
filterByCategory(category: string) {
if (category) {
this.filteredProducts = this.products.filter(product => product.category === category);
} else {
this.filteredProducts = this.products;
}
}
}
Explanation of the filtering logic:
- The method
filterByCategory
takes acategory
parameter as input. - The first statement checks if the user has provided a valid value for filtering by category.
- Inside the
if
block:
- The method filters an array by a callback function, creating a new array with only the satisfying elements.
- The callback function checks if each element matches the selected one. If the condition is met, the element is included in the filtered array.
- If the provided value is not valid (i.e., false), the block executes, including all products in the array without filtering.
Let’s say, we are running our application locally and port 4200. Then our URL could be similar to https://localhost:4200/products?category=electronics&maxPrice=50000&minPrice=10000.
Let’s break down this URL.
- Base URL:
[https://localhost:4200](https://localhost:4200/)
(Assuming your application is running on port 4200 with the URL above).
- This is the base URL of our application. It’s the address where our application is hosted. In this case, it’s being hosted on our local machine at port 4200.
- Route Path:
/products
- After the base URL, the path
/products
indicates that the user is accessing the "products" route or page of your application.
- Query Parameters:
?category=electronics&maxPrice=50000&minPrice=10000
- The
?
character is used to start the query parameters section of the URL. They are key-value pairs separated by&
(ampersand) symbols.
- Category Query Parameter:
category=electronics
- The first query parameter is
category=electronics
. Here,category
is the key, andelectronics
is the value. This indicates that the user is interested in products belonging to the "electronics" category.
- Max Price Query Parameter:
maxPrice=50000
- The second query parameter is
maxPrice=50000
. This means the user wants to filter products with a maximum price of $50,000.
- Min Price Query Parameter:
minPrice=10000
- The third query parameter is
minPrice=10000
. This indicates that the user wants to filter products with a minimum price of $10,000.
Sample Picture,
Query Params Filter
Now, Let’s Use Query Parameters in Searching.
Let’s say, you have a list of products and you want to allow users to search for products by name, category, and price range, let’s implement this feature step by step:
Sample HTML for this could be:
<form>
<input type="text" name="search" placeholder="Search by name" />
<select name="category">
<option value="">All Categories</option>
<option value="electronics">Electronics</option>
<option value="clothing">Clothing</option>
<!-- Other category options -->
</select>
<input type="number" name="minPrice" placeholder="Min Price" />
<input type="number" name="maxPrice" placeholder="Max Price" />
<button type="submit">Search</button>
</form>
Search Handling in Component:
Assuming you have a component named SearchComponent
:
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
@Component({
selector: 'app-search',
templateUrl: './search.component.html',
styleUrls: ['./search.component.css']
})
export class SearchComponent implements OnInit {
constructor(private route: ActivatedRoute, private router: Router) { }
ngOnInit() {
this.route.queryParamMap.subscribe(params => {
const searchQuery = params.get('search');
const category = params.get('category');
const minPrice = params.get('minPrice');
const maxPrice = params.get('maxPrice');
// Perform search logic based on query parameters
this.performSearch(searchQuery, category, minPrice, maxPrice);
});
}
performSearch(searchQuery: string, category: string, minPrice: number, maxPrice: number) {
// Implement search logic here using the provided parameters
// You can update the component's properties or fetch filtered data from a service
}
onSearchSubmit(formValues: any) {
const queryParams = {
search: formValues.search,
category: formValues.category,
minPrice: formValues.minPrice,
maxPrice: formValues.maxPrice
};
// Use router navigation to update query parameters
this.router.navigate([], {
relativeTo: this.route,
queryParams: queryParams,
queryParamsHandling: 'merge'
});
}
}
Explanation of the Logic:
- The
SearchComponent
subscribes to changes in the query parameters using thequeryParamMap
observable from theActivatedRoute
. - Inside the
ngOnInit
method, the query parameters are extracted using theparams.get()
method. - The
performSearch
method is responsible for executing the actual search logic based on the query parameters. You can implement this logic using the provided parameters (search query, category, min and max prices). - The method collects search form values and constructs a search-related object upon submission.
- The method updates query parameters in the URL while preserving existing ones and adding new ones.
Now, users can simply input their search criteria into the form, submit it, and witness the URL being updated with the relevant query parameters. The system then utilizes these parameters to execute the search logic and showcase the fitting results.
Hope, You find this article helpful.
Follow me Please Follow me on Twitter, Linkedin, and Facebook.