“Query Parameter in Angular for Better User Experience”-(Angular No-12)

Gondi
2 min readSep 15, 2024

--

In Angular, query parameters are used to pass additional data in the URL without affecting the route path. They can be useful for filtering data, passing optional parameters, or sharing state between components.

Here’s how to work with query parameters in Angular:

1. Setting Query Parameters

You can use the Router service to programmatically set or navigate to routes with query parameters.

Example:

import { Component } from '@angular/core';
import { Router } from '@angular/router';

@Component({
selector: 'app-example',
template: `<button (click)="navigateWithQuery()">Go with Query Params</button>`
})
export class ExampleComponent {
constructor(private router: Router) {}

navigateWithQuery() {
this.router.navigate(['/products'], { queryParams: { page: 1, sort: 'asc' } });
}
}

Here, the URL would become something like http://localhost:4200/products?page=1&sort=asc.

2. Reading Query Parameters

You can read the query parameters in a component using the ActivatedRoute service.

Example:

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

@Component({
selector: 'app-product-list',
template: `<p>Page: {{ page }}</p><p>Sort: {{ sort }}</p>`
})
export class ProductListComponent implements OnInit {
page: number;
sort: string;

constructor(private route: ActivatedRoute) {}

ngOnInit() {
this.route.queryParams.subscribe(params => {
this.page = params['page'];
this.sort = params['sort'];
});
}
}

This will subscribe to the query parameters and retrieve the values when they change.

3. Preserving Query Parameters

When navigating from one route to another, you can preserve the query parameters using the queryParamsHandling option.

Example:

this.router.navigate(['/other-route'], { queryParamsHandling: 'preserve' });

This will keep the current query parameters in the URL when navigating to the new route.

4. Appending New Query Parameters

You can also merge the new query parameters with the existing ones:

this.router.navigate(['/other-route'], { queryParams: { newParam: 'value' }, queryParamsHandling: 'merge' });

This appends or merges the new query parameters with the existing ones.

With these methods, you can manage query parameters effectively in Angular.

--

--

Responses (1)