Output and EventEmitter used together to pass data from Child component to Parent component. EventEmitter emits the data that can be received by parent component. In the below example We have two components appComponent(parent component) and childComponent(child components) child component contains textbox and parent component shows the data when user enters in the child component. Here we have used Two-way binding, we can also use ngModelChange event.

Example:


child-component.component.html

<div style="border:1px solid chocolate; width:300px; height: 120px; padding: 10px 10px">

   <b> Child component</b><br><br>
   Type here : <input type="text" [(ngModel)]='inputValue'  />
  </div>

child-component.component.ts

import { Component, OnInit, Output, EventEmitter } from '@angular/core';
@Component({
  selector: 'child-component',
  templateUrl: './child-component.component.html',
  styleUrls: ['./child-component.component.css']
})
export class ChildComponentComponent{

private _inputValue:string;
get inputValue(){
  return this._inputValue;
}
set inputValue(value:string){
  this._inputValue=value;
  this.userName.emit(this._inputValue);
}

@Output() userName : EventEmitter<string>= new EventEmitter<string>();

}

app.component.html

<div style="border: 1px solid chocolate; height: 250px; width: 350px; padding: 10px 10px" >
 <span> <b>Parent component</b></span>
 <br><br>
 you entered {{messageFromChild}}
  <br><br>
  <child-component (userName)='OnDataChange($event)'></child-component>
</div>

app.component.ts

import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  public messageFromChild:string;
    OnDataChange(childData: string){
    this.messageFromChild=childData;
    }
}

Add FormsModule in the app.module.ts



That's It !!