Capture child component click event in parent component

To capture a child component’s click event in the parent component in Angular, you can use the following steps:

  • In the child component:
    • Use the @Output decorator to create an event emitter.
    • Emit the event when the click occurs.
   import { Component, EventEmitter, Output } from '@angular/core';

   @Component({
     selector: 'app-child',
     template: `<button (click)="onClick()">Click me</button>`
   })
   export class ChildComponent {
     @Output() clickEvent = new EventEmitter<any>();

     onClick() {
       this.clickEvent.emit('Data from child');
     }
   }
  • In the parent component:
    • Listen to the event using the event binding syntax ((clickEvent)) in the child component’s template.
    • Call a method in the parent component to handle the event.
   import { Component } from '@angular/core';

   @Component({
     selector: 'app-parent',
     template: `
       <app-child (clickEvent)="handleChildClick($event)"></app-child>
     `
   })
   export class ParentComponent {
     handleChildClick(data: any) {
       console.log('Click event received from child:', data);
     }
   }

Explanation:

  • The @Output decorator in the child component creates a custom event that the parent component can listen to.
  • The EventEmitter class is used to emit the event.
  • The emit() method is used to send data along with the event.
  • The (clickEvent) syntax in the parent component’s template listens for the event emitted by the child component.
  • The handleChildClick() method in the parent component is called when the event is emitted.

This way, you can effectively capture and handle child component events in the parent component in Angular.

FavoriteLoadingAdd to favorites
Spread the love

Author: Shahzad Khan

Software developer / Architect