Learnitweb

Event binding in Angular

Applications are built for users and it is obvious that users will interact with the application. User can fill input form and submit the form by clicking button. All these are examples of events performed by users. Whenever an event occurs, application should listen and respond to that event.

Using event binding we can listen to the events and respond. Few examples of events are keystroke, click and mouse movement. Event binding enables us to listen to the event and execute code which will be executed as a response to that event.

Syntax of event binding

(target-event-name)="template statement"

Syntax of event binding includes target event name in parentheses to the left of = and a template statement within quotes to the right of the =.

Let us see and example.

<button (click)="onDelete()">Delete</button>

Here, click event of button binds to the onDelete method of the component. Event binding will listen to the click event of the button and will call onDelete method of component whenever the button is clicked.

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

@Component({
  selector: 'app-root',
  template: `<button type="button" (click)="onSave()">Save</button>`,
})
export class AppComponent {
  onSave() {
    alert('button clicked');
  }
}

Event object – $event

$event, the event object contains the information about the event. Target event determines the type and information contained by $event object. If the target event is a native DOM element event, then $event is a DOM event object. If the event is from a component or directive then $event is of the shape of component or directive.

Let us change the above code to pass event object.

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

@Component({
  selector: 'app-root',
  template: `<button type="button" (click)="onSave($event)">Save</button>`,
})
export class AppComponent {
  onSave(eventObhect) {
    console.log(eventObject);
  }
}

Event object in this case is PointerEvent with properties target, clientX, clientY, pointerType etc.

Conclusion

In this article we discussed event binding. In the next article we’ll discuss how to raise custom events with EventEmitter. Happy learning!