Tuesday, May 2, 2023

Angular- Event Binding

In Angular, events are handled by using the following syntax-

(event name)="event handler method"

For example-


Above, (click) binds the button click event and onShow() statement calls the onShow() method of a component.

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

@Component({
  selector: 'app-root',
  template: '',
})
export class AppComponent {
  onShow() {
    console.log('Show button clicked!');
  }
}

Output of above code

click event output

$event

When an event is raised, we may need to pass some value to the event handler function. This value can be number, string, or an object that contains information about an event.

We can pass the number or string value to the event handler function, as shown below


Angular includes $event that contains the information about an event. The type of $event depends on the target event, e.g., if the target event is a native DOM element event, then it is an object.


A component should define the onClick($event) method where the type of the parameter can be KeyboardEvent, MouseEvent, etc. If you don't know the exact event type, they use “any” type, as shown below.

onClick(event:any) {
    console.log(event);
  }
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: '',
})
export class AppComponent {
  onClick(event: any) {
    console.log(event);
  }
}

Output of above code

Learn more about event binding.

No comments:

Post a Comment

^ Scroll to Top