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:
- Using the EventEmitter class
- 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:
How to pass data between a child component and parent component using shared service in Angular
Here’s an example of how to pass a variable from a child component to a parent component using a shared service in…medium.com