Summary:
When you use the routerLink
directive in Angular, it automatically encodes the URL by calling the encodeURI
function on the value passed to it.
Detailed Explanation
The reason behind this behavior is that when a complete URL is directly passed to the routerLink
, it triggers the serializeUrl
method within the directive. This method internally calls the serialize
function of urlSerializer
. You can view the implementation of the serialize method here.
serialize(tree: UrlTree): string {
const segment = `/${serializeSegment(tree.root, true)}`;
const query = serializeQueryParams(tree.queryParams);
const fragment =
typeof tree.fragment === `string` ? `#${encodeUriFragment(tree.fragment !)}` : '';
return `${segment}${query}${fragment}`;
}
export function encodeUriFragment(s: string): string {
return encodeURI(s);
}
A potential solution to address this issue would be to decode the URL using the built-in parseUrl
method provided by Angular's Router
. This method helps extract information such as the root
of the URL
, along with parameters and query strings.
Component
@Component({
...
})
export class AppComponent {
name = 'Angular 6';
url: any;
formattedUrl: any;
params: any = {};
constructor(private router: Router) {
}
ngOnInit() {
this.urlDecoder();
}
urlDecoder() {
this.url = '/a?i=1 a';
let parsedUrl = this.router.parseUrl(this.url);
console.log(parsedUrl)
const g: UrlSegmentGroup = parsedUrl.root.children[PRIMARY_OUTLET];
const s: UrlSegment[] = g.segments;
this.formattedUrl = `${s.map(p => p.path).join('/')}`; // needed to combine all consecutive segments
this.params = parsedUrl.queryParams;
}
}
HTML
<a [routerLink]="formattedUrl" [queryParams]="params">
Link Here
</a>
View Demo on StackBlitz