Professional Documents
Culture Documents
Sharing Data Between Component Using Input and Output Emitter
Sharing Data Between Component Using Input and Output Emitter
2. Child to Parent
Another way of sharing data is to emit from the child which can be listen by parent(Mostly like button
clicks etc.)
ChildComponent.ts
Import { Output, EventEmitter } from ‘’@angular/core’;
messageToSend:string=”Im from Child”;
@Output() messageEvent=new EventEmitter<string>(); //messageEvent is a variable for output emitter
sendMessage()
{
this.messageEvent.emit(this. messageToSend);
}
ChildCompoent.html
This is to be sent to parent: {{ messageToSend }}
<button (click)="sendMessage()">Send Message</button>
ParentComponent.ts
messageFromChild:string;
receiveMessage($event)
{
this.messageFromChild =$event;
}
ParentComponent.ts
<app-child></app-child> // this will load the child into parent
To sent value to child we modify it to
<app-child (messageEvent)=”receiveMessage($event)”> </app-child>
// the value inside () is the value of childOutput Emitter Value
ParentComponent.html
{{ messageFromChild }}