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>

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? Commented Oct 4, 2017 at 21:50
  • @KevinAud my apologies. I've updated the question with desired output = a traditional link with query parameters. Commented Oct 4, 2017 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. Commented Oct 4, 2017 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. Commented Oct 4, 2017 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. Commented Oct 4, 2017 at 23:06

1 Answer 1

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.