Aboodz
Aboodz

Reputation: 1584

How can I use a full URL string (with query params) in routerLink directive?

Consider this object that returns from an internal CMS

export declare interface ContentItem {
    id: string;
    title: string;
    subTitle: string;
    clickUrl: string;
    imageUrl: string;
    contentType: string;
    ...
}

The clickUrl will have a complete url that navigate to valid angular route. I was looking for a way to use this url in routerLink directive; something like this

<a [routerLink]="contentItem.clickUrl">click me</a>

My problem is when this url contains a query params. The directive will escape '?', '=' and '&' characters from the url.

I know that we can pass query params like this:

[queryParams]="{ articleId: contentItem.id }"

However, This does not work without stripping the query params part from clickUrl previously mentioned.

Upvotes: 5

Views: 1811

Answers (2)

As I am seeing your problem is basically that you need to persist previous query params but also add new. Angular comes with an option 'queryParamsHandling' to either preserve or merge. By default the query parameters are lost on any subsequent navigation action:

this.router.navigate(['/url'], { queryParamsHandling: 'preserve' });

It's also possible to use 'merge' option

e.g.

this.router.navigate(['/url?order=popular'], { queryParams: { filter: 'new'}, queryParamsHandling: 'merge' });
// result http://localhost/url?order=popular&filter=new

Upvotes: 0

ashfaq.p
ashfaq.p

Reputation: 5469

Instead of using routerLink, you can use the controller for this.

<a (click)="goTo(contentItem.clickUrl)">click me</a>

In controller:

this.goTo(url) {
  this.router.navigateByUrl(url);
}

Upvotes: 4

Related Questions