Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I conditionally use either [href] or [routerLink] on an anchor?

I need for the same anchor link to be pointed conditionally locally or to external resource. I tried

<a [href]="outside?externalUrl:null"  [routerLink]="outside?[]:['/route',id]" >test</a> 

But it doesn't work. I don't get any errors, but it points to the same local page and ignores the external URL. Any ideas?

Another option would be to construct the link, but I can't find any docs how to access routerLink inside a service

Edit: I know I can clone the whole link with *ngIf but I don't want to do it, my link contains a video tag with a buch of options

like image 581
Toolkit Avatar asked Jun 09 '17 04:06

Toolkit


People also ask

How do I use routerLink in anchor tag?

Adding routerLink attribute in anchor tag. Now, To make any element as link we must enclose it in anchor tag, therefore we will use <a> tag enclosing the <li> tag to make it a link.

Should I use href or routerLink?

routerLink is the attribute provided by angular to navigate to different components without reloading the page. Major difference between both is that href kills the state of the current page where routerLink doesnt lose the state of the page.

What is difference between routerLink and routerLink?

What is the difference between [routerLink] and routerLink ? How should you use each one? They're the same directive. You use the first one to pass a dynamic value, and the second one to pass a static path as a string.

Can I use routerLink on Div?

Yes it can be attached to div tag, your route is probably wrong try add / in front of route.


1 Answers

The simplest way would be to use *ngIf / else:

<ng-container *ngIf="outside; else internalBlock">   <a [href]="externalUrl">External</a> </ng-container>  <ng-template #internalBlock>   <a [routerLink]="['/route', id]">Internal</a> </ng-template> 

EDIT#1: (Ugly workaround)

Since you don't want to use *ngIf (I still don't understand why), you can do this:

Template:

<a href="javascript:void(0)" (click)="handleClick(outside, '/route', id, externalUrl)">Link</a> 

Component:

handleClick(outside: boolean, internalUrl: string, internalId: string, externalUrl: string): void {   if (outside) {     window.location.href = externalUrl;     // You can also use Location class of Angular   } else {     this.router.navigate([`${internalUrl}/${internalId}`]);   } } 
like image 141
developer033 Avatar answered Sep 25 '22 02:09

developer033