Dynamic queryParams with a routerLink link in Angular
Asked Answered
S

1

3

I'm trying to pass a parameter to my routerLink within a loop. Here is what the array of objects looks like: enter image description here

Here is the loop with the routerLink link:

<li *ngFor="let Achievement of AllAchievements">

    example from multiple sources
    does not work with a variable 'x'. Outputs the letter x
    <a routerLink="page" [queryParams]="{x : 1}">anchor text</a> 

    example from multiple sources
    link is outputted /%5B'page',%20%7BAchievement.type%20:%20'hello'%7D%20%5D'
    <a routerLink="['page', {Achievement.type : 'hello'} ]">anchor text</a>

    outputs long/encoded string as param value 
    <a [routerLink]="['page']" queryParams="{ [Achievement.type] : 'hello' }">anchor text</a>
</li>

Desired output: <a href="page?position=hello"></a>

Shoeshine answered 4/10, 2017 at 21:40 Comment(5)
I'm not sure if I understand what you are asking... how do you want the behavior to differ from the code you provided?Seychelles
@KevinAud my apologies. I've updated the question with desired output = a traditional link with query parameters.Shoeshine
It would seem that you cannot make the key of the [queryParams] a dynamic value, but the value itself can be dynamic. You may have to rethink your approach.Spectroscopy
Wow, I think you're right @R. Richards. Can't find anything online. Docs say queryParams: {[k: string]: any} not finding anything about it not capable of being dynamic.Shoeshine
I tried to get it to work, but I ended up getting run time errors. Maybe you could create a payload key, and pass some values from the json in the value, perhaps with a good delimiter.Spectroscopy
M
3

Old question but I just encountered this and since there's no answers this is the solution I came up with. Simple middle-man function to process the key

getRouterParams (key: string, value: string) {
  return { [key]: value };
}

then your HTML would look like

<a [routerLink]="['page']" [queryParams]="getRouterParams(Achievement.type, 'hello')">anchor text</a>

Works with interpolated strings also, which was the case I need it for

<a [routerLink]="['page']" [queryParams]="getRouterParams('achievement__' + Achievement.type, 'hello')">anchor text</a>
Mope answered 21/2, 2022 at 16:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.