I have a situation where I need to pass a URL to routerLink via <a [routerLink]="targetUrl"></a>
. The targetUrl
is received as an @Input
from a parent component.
There are a number of cases I want to support:
/
../
/some/path/with?query=params
Because I want to support query parameters while not adding an extra input to the component, I decided to parse the query parameters from the targetUrl
using a pipe to get here:
<a
[routerLink]="targetUrl | urlPathParser"
[queryParams]="queryParams"
></a>
where queryParams
looks like:
public get queryParams(): Params {
return this.router.parseUrl(this.targetUrl).queryParams;
}
and the urlPathParser
pipe looks like follows:
@Pipe({
name: 'urlPathParser',
standalone: true,
})
export class UrlPathParserPipe implements PipeTransform {
private router = inject(Router);
public transform(value: string): string {
const parsedUrl = this.router.parseUrl(value);
parsedUrl.queryParams = {};
return this.router.serializeUrl(parsedUrl);
}
}
The problem with this approach is that ../
gets serialised to /../
which is wrong. I have read that this is just the behaviour of the default serializer.
Is there some other way that I would be able to support parent navigation while keeping things relatively simple as they are now and without really adding an extra input binding (the chain to get to this component is quite long by now)?
0
Why don’t you just pass the url to routerLink as is, the router Link can handle query params going as string. Query params is not needed nor the pipe.
<a
[routerLink]="targetUrl"
></a>
1