Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 1

Sharing Data Between Component Using Input and Output Emitter

1. Parent To Child using Input Emitter


Child Component.ts
Import {Input} from ‘@angular/core’;
@Input() message:string;//Input Decorator value to receive from parent
ChildComponent.html
{{message}}
ParentComponent.ts
<app-child></app-child> // this will load the child into parent
To sent value to child we modify it to
<app-child [message]=”messageToSend”></app-child>
// the value inside [] is the value of childInput Emitter Value
messageToSend=”hello World”;

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 }}

You might also like