6

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.

2
  • The url is still relative, right? (it does not contains host) Commented Apr 15, 2018 at 6:58
  • Yes the url is relative without a host. Commented Apr 15, 2018 at 7:36

2 Answers 2

3

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);
}
Sign up to request clarification or add additional context in comments.

3 Comments

This question is for angular not angularjs. Also using a function to handle click event does not generate href on <a></a>; instead, it will create click event handler. This is not the best for SEO
the above solution is also for angular, not angularjs. And its a SPA, so seo will not work anyways.
Its not recommended to do this. The anchor needs the href. It will remove Accessibility features?
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.