How to pass data from child component to a parent component in Angular

Sameer Gurung
Fuzzy Code
Published in
2 min readJan 28, 2023

--

Passing data from a child component to a parent component in Angular can be done using several methods. Here are two common ways to accomplish this:

  1. Using the EventEmitter class
  2. Using a shared service

1. Using the EventEmitter class

One way to pass data from a child component to a parent component is by using the EventEmitter class. The child component can emit an event with the data, and the parent component can listen for that event and receive the data. Here's an example:

// child.component.ts

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

@Component({
selector: 'app-child',
template: `
<button (click)="sendData()">Send Data</button>
`
})
export class ChildComponent {
@Output() dataEvent = new EventEmitter<string>();
sendData() {
this.dataEvent.emit('Hello from the child component!');
}
}

In the parent component’s template, you can add the (dataEvent) event binding to the child component, and then create a method to handle the event.

<!-- parent.component.html -->

<app-child (dataEvent)="handleData($event)"></app-child>
// parent.component.ts

import { Component } from '@angular/core';

@Component({
selector: 'app-parent',
template: `
<app-child (dataEvent)="handleData($event)"></app-child>
`
})
export class ParentComponent {
handleData(data: string) {
console.log(data);
}
}

2. Using a shared service

another way to pass data from a child component to a parent component is by using a shared service. You can create a service that can hold the data, and then inject it into both the parent and child components. The child component can update the data in the service, and the parent component can subscribe to the service to receive the updates.

Check out the post below on how to use a shared service to pass data between parent and child:

--

--

Sameer Gurung
Fuzzy Code

A Software Engineer, who also turns to be a JavaScript enthusiast. Currently working with NodeJs, Angular, Ionic and AWS. Catch me: https://smrgrg.com