18

I am trying to use routerLink with a function as follows:

<a class="nav-link" [routerLink]="callHome(data)">Home </a>

callHome(data){
   //perform some operations
   this.router.navigate(["/home"]);
}

The problem here is whenever I refresh the page, without even clicking on Home, it automatically navigates to /home.

Another alternative I tried is:

<a class="nav-link" [routerLink]="['/home']">Home </a>

Here, although it works, I am not able to do the operations before navigating.

I cannot use a button and use (click) because I want it as a link as well. If I use a button, the link is gone.

How can I use [routerLink] alongwith a function call?

helloworld
  • 1,002
  • 3
  • 15
  • 27

5 Answers5

23

You should be able to place a (click) handler on the link element.

<a class="nav-link" [routerLink]="['/home']" (click)="doSomeLogic()">Home</a>

It should perform the (click) handler prior to navigating with the router link.

Wrokar
  • 963
  • 7
  • 17
6

You can try like this also.. If you have manipulation in routerlink..

<a class="nav-link" routerLink="{{callHome(data)}}">Home </a>

It works in both methods..

<a class="nav-link" routerLink="{{otherMethod()}}" (click)="callHome(data)">Home </a>

I have tried it in angular 7, it is working..

Deepa
  • 850
  • 1
  • 10
  • 11
5

Simply add a (click) event to the <a> tag as well. See this stackblitz in action.

Felix Lemke
  • 6,189
  • 3
  • 40
  • 67
3

You simply must affect the string value of the route.... like this:

callHome(data){    
    //perform some operations    
    return "/home"; 
}

As stated in that stackoverflow: Angular 5 click bind to anchor tag

You probably want to add the class btn to the tag to make it works like this:

<a class="btn" (click)="callHome(data)">Home </a>
JFPicard
  • 5,029
  • 3
  • 19
  • 43
0

I am using Angular with Ionic, and I had to set the routerLink to null and use the (click) event.

<ion-item routerLink="{{null}}" (click)="logOut()" lines="none" detail="false">
  <ion-icon slot="start" name="log-out-outline" class="log-out-icon"></ion-icon>
  <ion-label>Log Out</ion-label>
</ion-item>

This ensures you get NO ionic routing animations AND full keyboard accessibility.

Todd Hale
  • 480
  • 8
  • 15