Angular: append query parameters to URL

95,537

Solution 1

This could be archived by using the Router class:

Using a component:

import { Router, ActivatedRoute } from '@angular/router';

@Component({})
export class FooComponent {
   constructor(
     private _route: ActivatedRoute,
     private _router: Router
   ){}

   navigateToFoo(){
     // changes the route without moving from the current view or
     // triggering a navigation event,
     this._router.navigate([], {
      relativeTo: this._route,
      queryParams: {
        newOrdNum: '123'
      },
      queryParamsHandling: 'merge',
      // preserve the existing query params in the route
      skipLocationChange: true
      // do not trigger navigation
    });
   }
}

For more info check this book and the angular Router API

Solution 2

I had to adjust Jota.Toledos answer a bit so that it works for me, I had to take out the second and the last property of the extras - object:

   navigateToFoo(){
     this._router.navigate([], {
      queryParams: {
        newOrdNum: '123'
      },
      queryParamsHandling: 'merge',
    });
   }

Solution 3

You should write

let params = new HttpParams();
params = params.append('newOrdNum','123');

Solution 4

this.router.navigate(['.'], { relativeTo: this.route, queryParams: { 'a': 'b' }, queryParamsHandling: 'merge', skipLocationChange: true});

router: Router route: ActivatedRoute

Solution 5

You'll want to take the current state of the query parameters from the Angular Router, modify those props (add / delete parameters), then reassign it using the Router:

// Make sure to import and define the Angular Router and current Route in your constructor
constructor(
  private router: Router,
  private route: ActivatedRoute
) {}

...
...
...

// Take current queryParameters from the activated route snapshot
const urlParameters = Object.assign({}, this.route.snapshot.queryParams); 

// Need to delete a parameter ?
delete urlParameters.parameterName;

// Need to add or updated a parameter ?
urlParameters.parameterName = newValue;

// Update the URL with the Angular Router with your new parameters
this.router.navigate([], { relativeTo: this.route, queryParams: urlParameters });


You could even go further and build a utility function to do this:

handleUrlParameters(paramsToAdd: {param: string}[], paramsToDelete?: string[]) {
  const urlParameters = Object.assign({}, this.route.snapshot.queryParams); 

  paramsToDelete.forEach(param => delete urlParameters[param]);

  Object.keys(paramsToAdd).forEach(param => urlParameters[param] = paramsToAdd[param]);

  this.router.navigate([], { relativeTo: this.route, queryParams: urlParameters });
}

And then you simply call handleUrlParameters with an object mapping a parameter to new values, or an array of parameter names to delete.

Share:
95,537

Related videos on Youtube

None
Author by

None

Updated on February 02, 2021

Comments

  • None
    None over 3 years

    Im using this:

        import { HttpParams } from '@angular/common/http';
        let params = new HttpParams();
        params.append('newOrdNum','123');
    

    But this is not working, i dont append param in url. Any suggestion?

    • Salim Ibrohimi
      Salim Ibrohimi over 6 years
      You want param like example.com/newordnum/123?
    • Jota.Toledo
      Jota.Toledo over 6 years
    • None
      None over 6 years
      i want to append on existing params. I have something like this : example.com?param1=111 and now i want to append to get example.com?param1=111&newOrdNum=123
    • None
      None over 6 years
      @Jota.Toledo its not add param in url with your example
    • Jota.Toledo
      Jota.Toledo over 6 years
      Are you trying to send a request with query parameters or to change the current state of the browser URL? If its the second, then you need to explain better what you are trying to archive
    • None
      None over 6 years
      i just want to append param to url...i'm gona handle that param on some other step..but right now just to append on existing url where i have other params
    • Tisha
      Tisha over 4 years
      when your query params are changed, does that reflect in the url as well?
  • None
    None over 6 years
    how to only append on existing with router? without writing path
  • Salim Ibrohimi
    Salim Ibrohimi over 6 years
    @None: are using Router
  • Salim Ibrohimi
    Salim Ibrohimi over 6 years
    @None: read this doc please: angular.io/api/common/http/HttpParams
  • Omar
    Omar about 6 years
    should I be able to see it in the URL or this is behind the scene?
  • Omar
    Omar about 6 years
    when skipLocationChanges is true then the url does not show it. which is fine. but i havent figured out what happens when it is false... Do you know?
  • Tisha
    Tisha over 4 years
    when your query params are changed, does that reflect in the url as well?
  • Tisha
    Tisha over 4 years
    when your query params are changed, does that reflect in the url as well?
  • Tisha
    Tisha over 4 years
    What if this was a google map and the latitude and longitude were to be appended to the url such that any panning action on the map by the user would also cause the query params in the url to get updated as the lat/lon would change?
  • Isuru
    Isuru about 3 years
    When skipLocationChanges is false URL shows the params
  • Arj 1411
    Arj 1411 over 2 years
    I have the same requirement but a slight difference. I need to add a token to all the route urls? Can we achieve this in a generic way than adding to every router.navigate()?