How to Add query parameters to the Current URL without Reloading in Angular?

To add query parameters to the current URL without reloading the page, you can use the router.navigate() method with a few extras.

The first parameter in the navigate() method is an array which allows you to specify the route on which you want to navigate.

But, in our case, we want to remain on the current route. Therefore, we have to keep this array empty.

This is what you need to add to your ts file:

constructor(private router: Router, private route: ActivatedRoute) {
}

addParams(){
  this.router.navigate(
    [],  // Remain on current route
    {
      relativeTo: this.route,
      queryParams: {
        param1: 'param1_value',
        param2: 'param2_value',
        // Add other parameters
      },
      queryParamsHandling: 'merge'  // Merge new params with existing params

  });
}

This will add the param1 and param2 to your current route along with their values without reloading the page:

Add query parameters to the current URL without reloading in angular

Get query parameters from the current Route

To get the query parameters from the current route, you can subscribe to the queryParams observable of the ActivatedRoute.

The queryParams returns you an observable which on subscribing gives you an object as a response that contains all the parameters along with their values.

This is how you can subscribe to the queryParams observable in your ts file and get the result:

constructor(private route: ActivatedRoute) { 
}

getParams(){
  this.route.queryParams.subscribe(
    params=>{
      console.log(params);
      
      // Output:
      // {
      //   param1: "param1_value"
      //   param2: "param2_value"
      // }
    }
  );
}

If you want to get the query parameters on page load, you have to subscribe to the queryParams observable in the ngOnInit() life cycle hook.

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.