Angular: How to update queryParams without changing route

后端 未结 8 523
日久生厌
日久生厌 2020-12-07 09:01

I am trying to update (add, remove) queryParams from a component. In angularJS, it used to be possible thanks to :

$location.search(\'f\', \'filters[]\'); //         


        
相关标签:
8条回答
  • 2020-12-07 09:03

    If you want to change query params without change the route. see below example might help you: current route is : /search & Target route is(without reload page) : /search?query=love

        submit(value: string) {
          this.router.navigate( ['.'],  { queryParams: { query: value } })
            .then(_ => this.search(q));
        }
        search(keyword:any) { 
        //do some activity using }
    

    please note : you can use this.router.navigate( ['search'] instead of this.router.navigate( ['.']

    0 讨论(0)
  • 2020-12-07 09:07

    @Radosław Roszkowiak's answer is almost right except that relativeTo: this.route is required as below:

    constructor(
      private router: Router,
      private route: ActivatedRoute,
    ) {}
    
    changeQuery() {
      this.router.navigate(['.'], { relativeTo: this.route, queryParams: { ... }});
    }
    
    0 讨论(0)
  • 2020-12-07 09:08

    You can navigate to the current route with new query params, which will not reload your page, but will update query params.

    Something like (in the component):

    constructor(private router: Router) { }
    
    public myMethodChangingQueryParams() {
      const queryParams: Params = { myParam: 'myNewValue' };
    
      this.router.navigate(
        [], 
        {
          relativeTo: activatedRoute,
          queryParams: queryParams, 
          queryParamsHandling: 'merge', // remove to replace all query params by provided
        });
    }
    

    Note, that whereas it won't reload the page, it will push a new entry to the browser's history. If you want to replace it in the history instead of adding new value there, you could use { queryParams: queryParams, replaceUrl: true }.

    EDIT: As already pointed out in the comments, [] and the relativeTo property was missing in my original example, so it could have changed the route as well, not just query params. The proper this.router.navigate usage will be in this case:

    this.router.navigate(
      [], 
      {
        relativeTo: this.activatedRoute,
        queryParams: { myParam: 'myNewValue' },
        queryParamsHandling: 'merge'
      });
    

    Setting the new parameter value to null will remove the param from the URL.

    0 讨论(0)
  • 2020-12-07 09:08

    The answer with most vote partially worked for me. The browser url stayed the same but my routerLinkActive was not longer working after navigation.

    My solution was to use lotation.go:

    import { Component } from "@angular/core";
    import { Location } from "@angular/common";
    import { HttpParams } from "@angular/common/http";
    
    export class whateverComponent {
      constructor(private readonly location: Location, private readonly router: Router) {}
    
      addQueryString() {
        const params = new HttpParams();
        params.append("param1", "value1");
        params.append("param2", "value2");
        this.location.go(this.router.url.split("?")[0], params.toString());
      }
    }
    

    I used HttpParams to build the query string since I was already using it to send information with httpClient. but you can just build it yourself.

    and the this._router.url.split("?")[0], is to remove all previous query string from current url.

    0 讨论(0)
  • 2020-12-07 09:11

    I ended up combining urlTree with location.go

    const urlTree = this.router.createUrlTree([], {
           relativeTo: this.route,
           queryParams: {
               newParam: myNewParam,
           },
           queryParamsHandling: 'merge',
        });
    
        this.location.go(urlTree.toString());
    

    Not sure if toString can cause problems, but unfortunately location.go, seems to be string based.

    0 讨论(0)
  • 2020-12-07 09:15

    In Angular 5 you can easily obtain and modify a copy of the urlTree by parsing the current url. This will include query params and fragments.

      let urlTree = this.router.parseUrl(this.router.url);
      urlTree.queryParams['newParamKey'] = 'newValue';
    
      this.router.navigateByUrl(urlTree); 
    

    The "correct way" to modify a query parameter is probably with the createUrlTree like below which creates a new UrlTree from the current while letting us modify it using NavigationExtras.

    import { Router } from '@angular/router';
    
    constructor(private router: Router) { }
    
    appendAQueryParam() {
    
      const urlTree = this.router.createUrlTree([], {
        queryParams: { newParamKey: 'newValue' },
        queryParamsHandling: "merge",
        preserveFragment: true });
    
      this.router.navigateByUrl(urlTree); 
    }
    

    In order to remove a query parameter this way you can set it to undefined or null.

    0 讨论(0)
提交回复
热议问题