In Angular is possible to pass data from a child component to a parent component using the @Output decorator and an EventEmitter, like this:

  1. Child Component (Sender): In the child component, define an @Output property with an EventEmitter.
  2. This property will emit an event containing the data you want to pass to the parent component.
   import { Component, EventEmitter, Output } from '@angular/core';

   @Component({
     selector: 'app-child',
     template: `
       <button (click)="sendData()">Send Data to Parent</button>
     `,
   })
   export class ChildComponent {
     @Output() dataEvent = new EventEmitter<string>();

     sendData() {
       const dataToSend = 'Data from Child';
       this.dataEvent.emit(dataToSend);
     }
   }
  1. Parent Component (Receiver):
    • In the parent component, need to bind to the @Output property of the child component and define a method to handle the emitted event.
   import { Component } from '@angular/core';
   @Component({
     selector: 'app-parent',
     template: `
       <app-child (dataEvent)="receiveData($event)"></app-child>
       <p>Data received from Child: {{ receivedData }}</p>
     `,
   })
   export class ParentComponent {
     receivedData: string;

     receiveData(data: string) {
       this.receivedData = data;
     }
   }

In the parent component’s template, (dataEvent)="receiveData($event)" binds to the dataEvent event of the child component and calls the receiveData method when the event is emitted.

With this setup, when the “Send Data to Parent” button in the child component is clicked, it emits the dataEvent event with the data “Data from Child.”

The parent component captures this event and updates the receivedData property, which is displayed in the parent component’s template.

And it’s done!

By davs