Attaching click to anchor tag in angular

AngularAnchorMouseclick Event

Angular Problem Overview


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.

Angular Solutions


Solution 1 - Angular

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 - Angular

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 - Angular

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 - Angular

<a href="#" (click)="onGoToPage2()">Go to page 2</a>

Solution 5 - Angular

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 6 - Angular

You can try something like this:

<a href="javascript: void(0);" (click)="method()">

OR

<a href="javascript: void(0);" [routerLink]="['/abc']">

Solution 7 - Angular

I had issues with the page reloading but was able to avoid that with routerlink=".":

<a routerLink="." (click)="myFunction()">My Function</a>

I received inspiration from the Angular Material docs on buttons: https://material.angular.io/components/button/examples

UPDATE I've started using routerLink="" since Angular 12. I was finding that routerLink="." was routing me to a parent page.

Solution 8 - Angular

<a href="javascript:void(0);" (click)="onGoToPage2()">Go to Page 2</a>

Solution 9 - Angular

I was able to implement this successfully

<a [routerLink]="['/login']">abc</a>

Solution 10 - Angular

I had to combine several of the answers to get a working solution.

This solution will:

  • Style the link with the appropriate 'a' styles.

  • Call the desired function.

  • Not navigate to http://mySite/#

    <a href="#" (click)="!!functionToCall()">Link</a>

Solution 11 - Angular

I have encountered this issue in Angular 5 which still followed the link. The solution was to have the function return false in order to prevent the page being refreshed:

html
<a href="" (click)="openChangePasswordForm()">Change expired password</a>
ts
openChangePasswordForm(): boolean {
  console.log("openChangePasswordForm called!");
  return false;
}

Solution 12 - Angular

You can use routerLink which is an alternative of href for angular 2.** Use routerLink as below in html

<a routerLink="/dashboard">My Link</a>

and make sure you register your routerLink in modules.ts or router.ts like this

const routes: Routes = [
  { path: 'dashboard', component: DashboardComponent }
]

Solution 13 - Angular

I have examined all the above answer's, We just need to implement two things to work it as expected.

Step - 1: Add the (click) event in the anchor tag in the HTML page and remove the href=" " as its explicitly for navigating to external links, Instead use routerLink = " " which helps in navigating views.

<ul>
  <li><a routerLink="" (click)="hitAnchor1($event)"><p>Click One</p></a></li>
  <li><a routerLink="" (click)="hitAnchor2($event)"><p>Click Two</p></a></li>
</ul>

Step - 2: Call the above function to attach the click event to anchor tags (coming from ajax) in the .ts file,

  hitAnchor1(e){
      console.log("Events", e);
      alert("You have clicked the anchor-1 tag");
   }
  hitAnchor2(e){
      console.log("Events", e);
      alert("You have clicked the anchor-2 tag");
   }

That's all. It work's as expected. I created the example below, You can have a look:-

https://stackblitz.com/edit/angular-yn6q6t

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser407283View Question on Stackoverflow
Solution 1 - AngularVickyView Answer on Stackoverflow
Solution 2 - AngularPatrickWView Answer on Stackoverflow
Solution 3 - AngularAndrew LandsverkView Answer on Stackoverflow
Solution 4 - AngularNeutrinoView Answer on Stackoverflow
Solution 5 - AngularBlueCaretView Answer on Stackoverflow
Solution 6 - AngularGasparView Answer on Stackoverflow
Solution 7 - AngularMike DalrympleView Answer on Stackoverflow
Solution 8 - AngularaungyeView Answer on Stackoverflow
Solution 9 - AngularJaimin PatelView Answer on Stackoverflow
Solution 10 - AngularFrancisco d'AnconiaView Answer on Stackoverflow
Solution 11 - AngularAlexei - check CodidactView Answer on Stackoverflow
Solution 12 - AngularSamim AhmedView Answer on Stackoverflow
Solution 13 - AngularNaheed ShareefView Answer on Stackoverflow