Reputation: 115
I have a side navigation bar in my application. All the icons in the side navigation point to different route. One of the icons should point me to a route with a query param. Example- localhost:4200/test?t=1
.
I have an interface for my navigation items that looks like this.
export interface NavigationItem {
link: string;
parameters?: string;
icon: string;
}
I have an array of these Navigation items that I loop over on my side navigation bar. One of the items in the array is this-
{
link: 'test',
parameters: '{t:1}',
icon: 'newIcon',
}
This is the code snippet in my *ngFor
<a [routerLink]="[item.link]" [queryParams]="item.parameters" routerLinkActive="active" class="navigation-item">
<mat-icon matListIcon class="icon">{{ item.icon }}</mat-icon>
</a>
I was expecting the route localhost:4200/test?t=1
to open on the icon click. But the route that's being formed is localhost:4200/test?0=%7B&1=t&2=:&3=1&4=%7D
Can you tell me what's going wrong?
Upvotes: 0
Views: 1314
Reputation: 1442
The right way to provide the parameters is using a Params type because of the queryParams doesn't accept a string value. Check your example with the solution from here.
Upvotes: 1
Reputation: 4127
All you need to assign type Params to your parameters
in interface
import { Params } from '@angular/router';
export interface NavigationItem {
link: string;
parameters?: Params;
icon: string;
}
Angular now consider parameters as router params hence avoid encoding it.
Hope this works.
Upvotes: 1
Reputation: 2295
It's because your parameters
field on NavigationItem
is a string so Angular is URL encoding it.
You can either convert parameters to be of type Params
(which I strongly recommend) or convert the string to an object using JSON.parse(item.parameters)
Your object should look like:
export interface NavigationItem {
link: string;
parameters?: Params;
icon: string;
}
And you can create it as:
const item = {
link: 'test',
parameters: {
t: 1
},
icon: 'newIcon',
} as NavigationItem
Upvotes: 2
Reputation: 71911
The parameters should be of type Params
, otherwise it encodes the string you pass in to be usable as a URL
export interface NavigationItem {
link: string;
parameters?: Params;
icon: string;
}
const item = {
link: 'test',
parameters: { t: 1 },
icon: 'newIcon',
}
Upvotes: 1