Angular Tutorials - Anchor bind tag click event example without href


In this blog post, we are going to learn how to bind the click event to the anchor tag.

Angular Tutorials - Anchor bind tag click event example without href

Anchor bind tag click event example 

In Angular applications, We have anchor tags used for following places

  • navigate to a different page
  • Add/remove HTML elements dynamically

You have to write a code to handle the anchor click event binding. Whenever use clicks on anchor event, It triggers the DOM event binding.

First, create an angular application using ng CLI command.

Anchor click event without href

Anchor tag has href and clicks event in legacy applications, but href are not supported

In HTML template file, please add anchor tag with click event like as follows

important points

  • href  is not required as it forwards the request
  • you can also add href="javascript: void(0);”
  • Add click event with calling function
  • Anchor displays as link, change the style as cursor =pointer to clickable like a button

<div style="text-align:center">
    <h1>
       Angular Button Click Event Example
    </h1>
<a class ='btn' style="cursor:pointer"(click)="clickme();">click me</a>
or
<a href="javascript: void(0);" (click)="clickme()"> click here

    <h2>{{msg}}</h2>
 </div>

In your typescript code


import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  msg:string;
  constructor() {

   }

   clickme(){
    this.msg='anchor tag is Clicked';
    return this.msg;
  }
}

 In applicaitons, you can navigate from one page to other page, This can be achieved using href in legacy jquery apps. In Angular application, same can be achieved with routerLink attribute as seen below

[Home](https://www.blogger.com/null)

router link path must be configured in router file

 { path: 'home', component: HomeComponent }
Similar Posts