Ben Racicot
Ben Racicot

Reputation: 5980

Dynamic queryParams with a routerLink link in Angular

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>

Upvotes: 3

Views: 2776

Answers (1)

iamsar
iamsar

Reputation: 1130

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>

Upvotes: 3

Related Questions