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?
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.
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.)
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.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With