How to pass event objects from template to component in Angular?
you can use the $event object in the template along with the event binding syntax. Here’s an example:
In the template, you can pass the $event object as an argument to the component method using event binding syntax. For example, to call a method named “handleClick” in the component when a button is clicked and pass the event object to it, you could use the following syntax:
<button (click)="handleClick($event)">Click me</button>
In the component, you can receive the event object as an argument in the method. For example, the handleClick() method in the component could look like this:
import { Component } from '@angular/core';@Component({ selector: 'app-root', template: '<button (click)="handleClick($event)">Click me</button>',})export class AppComponent { handleClick(event: MouseEvent) { console.log(event); // Output: MouseEvent object }}
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: '<button (click)="handleClick($event)">Click me</button>',
})
export class AppComponent {
handleClick(event: MouseEvent) {
console.log(event); // Output: MouseEvent object
}
In this example, the $event object is passed as an argument to the handleClick() method in the component using event binding syntax. The method then receives the event object as an argument and logs it to the console.
Note : that the type of the event object depends on the type of the event. In this example, the type of the event object is MouseEvent because the event being handled is a click event. If you were handling a different type of event, such as a keydown event, the type of the event object would be different (e.g. KeyboardEvent).