EventEmitter Parent to Child Communication

EventEmitter Parent to Child Communication

To enable communication from a parent component to a child component in Angular, you can utilize the EventEmitter class. This class serves as a mechanism for emitting events that notify the parent component of changes or actions occurring within the child component.

Here's a step-by-step guide on how to implement parent-to-child communication using EventEmitter in Angular:

1. Define the EventEmitter in the Child Component:

In the child component's class, import the EventEmitter class from @angular/core and create an instance of it. Decorate the property with the @Output() decorator to indicate that it emits events.

import { Component, EventEmitter, Output } from '@angular/core';

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
})
export class ChildComponent {
  @Output() childEvent = new EventEmitter<string>();

  // Child component methods and logic
}

2. Emit Events from the Child Component:

Within the child component, create a method that emits an event using the emit() method of the EventEmitter instance. Pass the data you want to send to the parent component as an argument to emit().

emitChildEvent() {
  this.childEvent.emit('Data from Child Component');
}

3. Bind Events in the Parent Component:

In the parent component's template, use event binding to connect the child component's event to a method in the parent component. This method will be called whenever the child component emits the event.

<app-child (childEvent)="handleChildEvent($event)"></app-child>

4. Handle Events in the Parent Component:

In the parent component's class, define a method that receives the emitted data from the child component. This method will be invoked when the child component emits the event.

handleChildEvent(data: string) {
  console.log('Received from Child Component:', data);
}

By following these steps, you can effectively establish parent-to-child communication using EventEmitter in Angular. This enables the parent component to react to events triggered within the child component and exchange data between them.


  • Date: