Attaching click to anchor tag in angular

198,173

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:

  1. Remove the href tag from <a> to prevent a page forwarding.
  2. Then just add your usual Angular click attribute and function.
  3. 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>
Share:
198,173

Related videos on Youtube

HDJEMAI
Author by

HDJEMAI

Angular/Java Developer

Updated on July 08, 2022

Comments

  • HDJEMAI
    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
      ranakrunal9 over 7 years
      you can use event.target.nodeName to know on which HTML tag click is fired.
    • Jai
      Jai over 7 years
      (click)='fn' can be used.
    • Admin
      Admin over 7 years
      @jai thanks i can't manipulate the ajax response i have to handle it from ts file
    • Karl
      Karl over 7 years
      Seems 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
      Martin about 7 years
      Can 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
    Neutrino over 6 years
    But that doesn't make it render like a link. It just looks like normal paragraph text.
  • PatrickW
    PatrickW over 6 years
    you can control looks with CSS. What do you want your link to look like?
  • Neutrino
    Neutrino over 6 years
    A 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
    Abhijit Jagtap over 6 years
    but # reloading page, is there any way to apply only click event on a href tag
  • Claies
    Claies over 6 years
    This 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
    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
    Vicky over 6 years
    You can use the same above code in HTML and in component.ts file use onGoToPage2() { window.location.href='http://www.cnn.com/'; //use the external url here } so,you can watch the click event also.
  • Neofish
    Neofish over 6 years
    Seems that the square brackets around routerLink are required for it to work as desired (without them it navigates as normal to /).
  • Andrew Landsverk
    Andrew Landsverk about 6 years
    Yes, you just need to add !! before your click call: (click)="!!onGoToPage2()"
  • Aico Klein Ovink
    Aico Klein Ovink almost 6 years
    This is still reloading page for me
  • user1131926
    user1131926 almost 6 years
    you can also try <a href (click)="onGoToPage2()">Go to page 2</a>
  • argoden
    argoden almost 6 years
    @AndrewLandsverk you should promote your comment to an asnwer
  • Andrew Landsverk
    Andrew Landsverk almost 6 years
    Thanks @argoden ! It has been converted.
  • Ziul
    Ziul almost 6 years
    I 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
    Techdive over 5 years
    And you cannot write it without an href .Otherwise it doesn't give me the required css for the anchor tag link.
  • Jette
    Jette over 5 years
    Works perfectly in Angular 7
  • Mike Poole
    Mike Poole over 5 years
    When adding a style to HTML you use an equal sign e.g. style="cursor: pointer;"
  • Captain Prinny
    Captain Prinny over 4 years
    @emirhosseini are you using it explicitly as [routerLink] and not routerLink ? that was tripping me up.
  • Stavm
    Stavm over 4 years
    this fails miserably when your route has query parameters i'll save you the scrolling, keep using href="javascript:void(0)".
  • rubmz
    rubmz over 4 years
    So it still regards the return value of the function ... not as clear as in the vanilla JS onClick="return function()" ...
  • Patrick Kelleter
    Patrick Kelleter over 3 years
    a 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
    Per Hornshøj-Schierbeck over 2 years
    you can have the href attribute without any value and this solution should work <a href (click)...>
  • Stefano
    Stefano almost 2 years
    This was the most useful answer. It solved my problem