[angular] Attaching click to anchor tag in angular

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.

This question is related to angular anchor mouseclick-event

The answer is


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


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>

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;
}

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

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


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!


I was able to implement this successfully

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

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

You can try something like this:

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

OR

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

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 }
]

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>


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


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.


Examples related to angular

error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class error TS1086: An accessor cannot be declared in an ambient context in Angular 9 TS1086: An accessor cannot be declared in ambient context @angular/material/index.d.ts' is not a module Why powershell does not run Angular commands? error: This is probably not a problem with npm. There is likely additional logging output above Angular @ViewChild() error: Expected 2 arguments, but got 1 Schema validation failed with the following errors: Data path ".builders['app-shell']" should have required property 'class' Access blocked by CORS policy: Response to preflight request doesn't pass access control check origin 'http://localhost:4200' has been blocked by CORS policy in Angular7

Examples related to anchor

How to open a link in new tab using angular? Attaching click to anchor tag in angular How to create a link to another PHP page Making href (anchor tag) request POST instead of GET? Difference between _self, _top, and _parent in the anchor tag target attribute How can I create a link to a local file on a locally-run web page? How to open link in new tab on html? Getting a link to go to a specific section on another page Pure CSS scroll animation Make anchor link go some pixels above where it's linked to

Examples related to mouseclick-event

Attaching click to anchor tag in angular Disallow Twitter Bootstrap modal window from closing How to simulate a mouse click using JavaScript? How to simulate a click by using x,y coordinates in JavaScript? How to use jQuery to show/hide divs based on radio button selection?