Use either routerLink or href based on value whether it is internal or external

121 views Asked by At

I want in my anchor elements to use either [routerLink] if the provided url is external or [href] whether it's internal url. The problem is i don't know what url it will be, because it comes from backend.

I tried to use directive and replace attribute like below:

this.el.nativeElement.setAttribute('routerLink', this.routerOrHref);

or

this.el.nativeElement.setAttribute('href', this.routerOrHref);

but using this solution makes routerLink useless, becuase it does not generate href.

Is there any solution to apply it for the code?

<a
  data-cy="footer-links"
  (click)="onNavigate(item)"
  [routerLink or href here based on if url is external or internal] = [item.url]
>

I actually do not want to put 2 anchor tags and determine which should be displayed like this:

<a *ngIf="extern" [routerLink]="link"></a>
<a *ngIf="!extern" [href]="link"></a>

It's important in terms of SEO for me to have valid href. And the requirement is to use Angular RouterLink in that case, when it is external link.

1

There are 1 answers

2
Khaled Ayed On

Since you don't want to use *ngIf you can do this:

<a
  data-cy="footer-links"
  (click)="onNavigate(item)"
>

and .ts file:

onNavigate(item) {
    this.extern ? this.router.navigate([`${externalUrl}`]) :
     window.location.href = internalUrl
    // You can also use Location class of Angular
}