The easiest way to pass / send data from child component to parent Component is using @Output decorator and event emitter as below
1. Import Event Emitter and Output decorator from @angualr/core in the child component
here we are passing data in “mydata” variable using “myParentData” Identifier
import { Component, OnInit, EventEmitter, Output } from '@angular/core';
2. Create event emmiter in child component with @Output decorator
@Output() public myChildEvent = new EventEmitter();
3. Add button in child component to fire the event
<button (click)="myEvent()"> Send Data to parent </button>
then in the function call event emitter in child component ts file
public myChildData = "This is message from Child Component";
myEvent(){
this.myChildEvent.emit(this.myChildData);
}
4. In the Parent Component bind event emitter to child component selector
here “captureChildData” is variable use to capture the data from child. and “$event” is used to get data from child component.
<app-child (myChildEvent)="captureChildData=$event"></app-child>
You can use “captureChildData” variable to html file to display data from child component
<h3> {{captureChildData}} </h3>
Parent.component.ts
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-parent', template: ` <h1> This is parent Compoenent </h1> <h3>{{captureChildData}}</h3> <hr> <app-child (myChildEvent)="captureChildData=$event"></app-child> `, styleUrls: ['./parent.component.css'] }) export class ParentComponent implements OnInit { public captureChildData; constructor() { } ngOnInit() { } }
child.component.ts
import { Component, OnInit, EventEmitter, Output } from '@angular/core'; @Component({ selector: 'app-child', template: ` <h2> This is Child Compoenent </h2> <button (click)="myEvent()"> Send Data to parent </button> `, styleUrls: ['./child.component.css'] }) export class ChildComponent implements OnInit { @Output() public myChildEvent = new EventEmitter(); public myChildData = "This is message from Child Component"; constructor() { } ngOnInit() { } myEvent(){ this.myChildEvent.emit(this.myChildData); } }