Angular Event Binding

In the previous article, we learned about Angular Style Binding. In this tutorial, we’ll learn about the most used and important topic, i.e., Event Binding. Event Binding is used to respond to the events raised by the user. There are many types of events such as click, mouseover, keydown, keypress, and many more.

What is Event Binding in Angular?

Angular Event Binding defines a method and binds that with an event or multiple events. Hence, when the event is triggered, the specified method will be called.

Let’s understand the event binding with the syntax:

<button (click)="onClick()">Click Me</button>

<h2>{{clicked}}</h2>
  • The click is a type of event which will occur when clicked on that particular HTML element.
  • Bind the function to the given event on the HTML element in the HTML.
  • The onClick() is the function defined in the ts file, which will be called when the user raises the event.

Example 1

In this example, we will learn how to call a function on click event in Angular.

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  title = 'my-app';
  clicked = " "
  onClick(){
    this.clicked = "Button Clicked"
  }
}

Inside the onClick() function, the clicked property is assigned with a String value “Button Clicked,” which will be executed when the function is called and displayed in the browser.

Output:

Angular event binding example 1

Sometimes we might want information about the event itself, i.e., information about the click event.

We can also achieve that by sending a parameter in the event handler, which is $event.

Let’s see the Syntax to understand it better:

<button (click)="onClick($event)">Click Me</button>

<h2>{{clicked}}</h2>

Here, $event gives all the information about the DOM event that was raised.

Example 2

In this example, we will learn how we can define the inline function on the click event of the angular component.

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  title = 'my-app';
  clicked = " "
  onClick(event : any){
    this.clicked = "The type of Event is " + event.type;
  }
}
  • In the component.ts file, we’ve passed the event as a parameter and assigned the type to the clicked property.
  • Type returns the event type as value.

Output:

Angular event binding example 2

Apart from click events, there are many more events to apply. However, the syntax remains the same.

Conclusion

We hope this article will clear all your doubts on Event Binding in Angular. Event Binding is one of the most used topics when we’re developing an app using Angular.

Read Next: Angular Template Reference Variables

Leave a Reply

Your email address will not be published. Required fields are marked *