angulartypescriptquery-stringangular-routerlinkangular12

Is it possible to use a constant as the property name in routerLink's queryParams?


I'm trying to navigate to the current page and change/add the query parameter "categoryId". If I do:

<a
      [routerLink]=""
      [queryParams]="{ categoryId: category!.id }"
      queryParamsHandling="merge"
>

It works fine, but I have a constant for the query param name, that way if I ever want to change it, I don't have to find every instance.

In the component.ts, I have the property:

categoryIdQueryParamName = QueryParamNames.CATEGORY_ID;

I have tried:

<a
  [routerLink]=""
  [queryParams]="{ {{'"' + categoryIdQueryParamName + '"' }}: category!.id }"
  queryParamsHandling="merge"
>

After looking at: https://stackoverflow.com/a/2274327/787958, I tried:

<a
  [routerLink]=""
  [queryParams]="{ [categoryIdQueryParamName]: category!.id }"
  queryParamsHandling="merge"
>

But, I'm still getting a compile error. If possible, what is the correct way to do this? Side note, I know I could do this programmatically with (click), but I am utilizing <a [routerLink]> to get the benefit of being able to right-click and open in a new tab.


Solution

  • Cleanest way is to do it in ts

    public get queryParams() {
        const p = {};
        p[QueryParamNames.CATEGORY_ID] = category!.id;
        return p;
    }
    
    <a [routerLink]="" [queryParams]="queryParams" queryParamsHandling="merge" >