In Angular 4, passing data from a child component to a parent component is done using EventEmitter and @Output. Here's the precise and complete process to achieve this:
1. Child Component:
Child Component Code:
import { Component, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-child',
template: `
<button (click)="sendData()">Send Data to Parent</button>
`
})
export class ChildComponent {
@Output() dataEmitter = new EventEmitter<string>();
sendData() {
const data = 'Hello from Child!';
this.dataEmitter.emit(data); // Emit data to parent
}
}
In the above child component:
2. Parent Component:
Parent Component Code:
import { Component } from '@angular/core';
@Component({
selector: 'app-parent',
template: `
<app-child (dataEmitter)="receiveData($event)"></app-child>
<p>Data received from Child: {{ childData }}</p>
`
})
export class ParentComponent {
childData: string;
receiveData(data: string) {
this.childData = data; // Receive data from the child and store it
}
}
In the above parent component: