Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using routerLink with a function call

Tags:

angular

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?

like image 500
helloworld Avatar asked Oct 18 '18 16:10

helloworld


People also ask

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 we use href instead of routerLink?

Always avoid href when using Angular or any other SPA. routerLink loads resources internal to Angular, and the page that loaded in the browser is never completely reloaded (and so app state is maintained.)

Can I add routerLink to div?

Yes it can be attached to div tag, your route is probably wrong try add / in front of route. You should avoid this and prefer a (click) + navigate programmatically approach since it will make your div "focusable" and Chrome by default adds a black outline to focused elements.

Can I use routerLink on button?

Using Router linksAfter Angular v4 we can directly add a routerLink attribute on the anchor tag or button. Consider the following template, where routerLink attribute added to the anchor tag. The routerLink directive on the anchor tags give the router control over those elements.


1 Answers

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>
like image 81
JFPicard Avatar answered Oct 11 '22 15:10

JFPicard