Attaching click to anchor tag in angular
Solution 1
You can use routerLink
(which is an alternative of href
for angular 2+) with click event as below to prevent from page reloading
<a [routerLink]="" (click)="onGoToPage2()">Go to page</a>
Solution 2
I think you are not letting Angular work for you.
In angular 2:
- Remove the
href
tag from<a>
to prevent a page forwarding. - Then just add your usual Angular click attribute and function.
- Add to
style: "cursor: pointer"
to make it act like a button
Solution 3
You just need to add !!
before your click method handler call: (click)="!!onGoToPage2()"
. The !!
will prevent the default action from happening by converting the return of your method to a boolean. If it's a void
method, then this will become false
.
Solution 4
I've been able to get this to work by simply using [routerLink]="[]"
. The square brackets inside the quotes is important. No need to prevent default actions in the method or anything. This seems to be similar to the "!!" method but without needing to add that unclear syntax to the start of your method.
So your full anchor tag would look like this:
<a [routerLink]="[]" (click)="clickMethod()">Your Link</a>
Just make sure your method works correctly or else you might end up refreshing the page instead and it gets very confusing on what is actually wrong!
Solution 5
<a href="#" (click)="onGoToPage2()">Go to page 2</a>
Related videos on Youtube
Comments
-
HDJEMAI almost 2 years
I am trying to attach click event to anchor tags (coming from ajax) and block the default redirection. How can I do it in angular ?
<ul> <li><a href="/abc"><p>abc</p></a></li> <li><a href="/abc1"><p>abc1</p></a></li> <li><a href="/abc2"><p>abc2</p></a></li> <li><a href="/abc3"><p>abc3</p></a></li> </ul>
In ts file:
constructor(elementRef: ElementRef, renderer: Renderer) { this.listenFunc = renderer.listen(elementRef.nativeElement, 'click', (event) => { event.preventDefault(); let target = event.target || event.srcElement || event.currentTarget; console.log(target); }); }
This will attach event to all elements, how can I limit this to anchor tag only ?
All helps appreciated.
-
ranakrunal9 over 7 yearsyou can use
event.target.nodeName
to know on which HTML tag click is fired. -
Jai over 7 years
(click)='fn'
can be used. -
Admin over 7 years@jai thanks i can't manipulate the ajax response i have to handle it from ts file
-
Karl over 7 yearsSeems you have to manipulate the JSON you get. parse it to an object; add or update properties and then assign updated JSON to target; maybe this gives you a hint: stackoverflow.com/questions/8702474/…
-
Martin about 7 yearsCan you explain how you get this HTML from ajax and insert it into the page? AHAH (AJAX HTML) used to be quite popular, even with Angularjs 1.x many templates were rendered on the serverside. Just haven't seen any use of AHAH with modern Angular or React.
-
-
Neutrino over 6 yearsBut that doesn't make it render like a link. It just looks like normal paragraph text.
-
PatrickW over 6 yearsyou can control looks with CSS. What do you want your link to look like?
-
Neutrino over 6 yearsA link, and I'd rather not have to mess around with manual styling just to make a link look like a link, as it should do anyway.
-
Abhijit Jagtap over 6 yearsbut # reloading page, is there any way to apply only click event on a href tag
-
Claies over 6 yearsThis question was asked over a year ago. It is unlikely that the Original Poster is still having this same issue, and therefore new answers should strive to provide as much detail as possible to show how the answer helps others who are having the same issue. This answer is more like a comment than a complete, researched, explained answer.
-
Marzieh Bahri over 6 years[routerLink] is for internal urls. What if we want to send the user to an external url and at the same time watch the click event?
-
Vicky over 6 yearsYou can use the same above code in HTML and in
component.ts
file useonGoToPage2() { window.location.href='http://www.cnn.com/'; //use the external url here }
so,you can watch the click event also. -
Neofish over 6 yearsSeems that the square brackets around routerLink are required for it to work as desired (without them it navigates as normal to /).
-
Andrew Landsverk about 6 yearsYes, you just need to add
!!
before your click call:(click)="!!onGoToPage2()"
-
Aico Klein Ovink almost 6 yearsThis is still reloading page for me
-
user1131926 almost 6 yearsyou can also try <a href (click)="onGoToPage2()">Go to page 2</a>
-
argoden almost 6 years@AndrewLandsverk you should promote your comment to an asnwer
-
Andrew Landsverk almost 6 yearsThanks @argoden ! It has been converted.
-
Ziul almost 6 yearsI learned the hard way that abusing this can make very confusing errors to other developers in the long run. When something in your onGoToPage2 function crashes, the anchor automatically redirects you to your home page which doesn't make any sense... using $event.preventDefault() at the beggining will produce more consistent crashes for other developers to figure out.
-
Techdive over 5 yearsAnd you cannot write it without an href .Otherwise it doesn't give me the required css for the anchor tag link.
-
Jette over 5 yearsWorks perfectly in Angular 7
-
Mike Poole over 5 yearsWhen adding a style to HTML you use an equal sign e.g.
style="cursor: pointer;"
-
Captain Prinny over 4 years@emirhosseini are you using it explicitly as
[routerLink]
and notrouterLink
? that was tripping me up. -
Stavm over 4 yearsthis fails miserably when your route has query parameters i'll save you the scrolling, keep using
href="javascript:void(0)"
. -
rubmz over 4 yearsSo it still regards the return value of the function ... not as clear as in the vanilla JS onClick="return function()" ...
-
Patrick Kelleter over 3 yearsa click listener with corresponding implementation is not the same as an href. you can not open a new tab with it for example. please dont replace all links in this world with click listeners - you are making the web a worse place this way.
-
Per Hornshøj-Schierbeck over 2 yearsyou can have the href attribute without any value and this solution should work <a href (click)...>
-
Stefano almost 2 yearsThis was the most useful answer. It solved my problem