How to Remove Query Params from URL in Angular?

In Angular, query parameters are a way to pass additional information between different routes and components by appending them at the end of the URL in the form of key-value pairs.

These query parameters are typically used to pass information such as search filters, sorting options, current page number etc.

Query parameters are added at the end of the URL using a question mark(?) in the form of key-value pairs where each key-value pair is separated by an ampersand(&).

For example:

/products?category=electronics&priceRange=100-500&sortBy=price

Removing Query Params From URL

To remove the query parameters from a URL, you can call the Router.navigate() method with the first parameter as an empty array.

When you pass an empty array to the Router.navigate() method, it stays on the current route and does not reload the page.

You can then set the value of the query parameter to null which you want to remove from the URL.

See the following example:

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

@Component({
  selector: 'app-products',
  templateUrl: './products.component.html',
  styleUrls: ['./products.component.scss']
})
export class ProductsComponent implements OnInit{

  constructor(
    private router: Router
  ){}

  ngOnInit(): void {}

  // Fires on button click
  removeQueryParams(){
    this.router.navigate(
      [],
      {
        queryParams: {
          category: null,   // Remove category query param
          priceRange: null, // Remove priceRange query param
        },
        queryParamsHandling: 'merge',
      }
    )
  }
}

Output:

Remove Query Params from URL in Angular

In the above example, the query parameters ‘category’ and ‘priceRange’ are removed from the URL as soon as we click the button.

Note: The queryParamsHandling option is set to 'merge', which ensures that the rest of the URL (path and other query parameters if any) remains unchanged.

If you want to remove all query parameters from the URL, you can set the value of each query parameter to null.

That’s all for this article. Thanks for reading!

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.

    View all posts