Kirtesh Shah
How to pass event object from template to component in Angular?

How to pass event objects from template to component in Angular?

By Kirtesh Shah in Angular on Dec 30 2021
  • Jay Pankhaniya
    Apr, 2023 14

    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:

    1. <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:

    1. import { Component } from '@angular/core';
    2. @Component({
    3. selector: 'app-root',
    4. template: '<button (click)="handleClick($event)">Click me</button>',
    5. })
    6. export class AppComponent {
    7. handleClick(event: MouseEvent) {
    8. console.log(event); // Output: MouseEvent object
    9. }
    10. }

    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).

    • 0


Most Popular Job Functions


MOST LIKED QUESTIONS