1

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.

Gigaxit
  • 11
  • 4

1 Answers1

0

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
}
Khaled Ayed
  • 1,121
  • 3
  • 12
  • 29
  • Thanks, but it's not actually what I was looking for. My focus is to provide valid href because of SEO. Navigation is already done and I am not sure if i can modify it. My requirement is to use routerLink when the link is external, and href when it's internal. I am not quite sure if it is possible to achieve that's why I'm asking. – Gigaxit Apr 06 '23 at 18:29
  • in that case I would recommend building a component that injects the platform, in which you could then do a ngIf else, to either render with href or routerlink – Caio Oliveira Apr 06 '23 at 19:49