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>

Ben Racicot
  • 5,332
  • 12
  • 66
  • 130
  • I'm not sure if I understand what you are asking... how do you want the behavior to differ from the code you provided? – Kevin Aud Oct 04 '17 at 21:50
  • @KevinAud my apologies. I've updated the question with desired output = a traditional link with query parameters. – Ben Racicot Oct 04 '17 at 21:53
  • 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. – R. Richards Oct 04 '17 at 22:29
  • 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. – Ben Racicot Oct 04 '17 at 22:55
  • 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. – R. Richards Oct 04 '17 at 23:06

1 Answers1

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>
iamsar
  • 1,080
  • 2
  • 15
  • 28