0

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.

ScubaSteve
  • 7,724
  • 8
  • 52
  • 65

1 Answers1

1

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" >
misha130
  • 5,457
  • 2
  • 29
  • 51
  • That works and is a very clean approach! One note, for strict TS to allow this, I had to do: `const p: Params = {};`. – ScubaSteve Jun 19 '21 at 19:53