TIL: How to pass data from child to parent component in Angular
Prayatna Bhattarai
Posted on October 25, 2020
A simple way to pass data from the child to the parent component using EventEmitter
.
I have a child component which holds a message object and I want to pass it back to the parent postMessage
component
message.component.ts
import { Component, EventEmitter, OnInit, Output } from "@angular/core";
@Component({
selector: "message",
templateUrl: "./message.component.html",
styleUrls: ["./message.component.css"]
})
export class MessageComponent implements OnInit {
message: IMessage;
@Output()
postMessageEvent = new EventEmitter();
constructor() {}
ngOnInit() {
//eg message - would basically come from user input though
this.message = {
value: "This is a message I like to post",
id: 1
};
}
handleClick() {
this.postMessageEvent.emit(this.message);
}
If you look closely, I have created an @Output
postMessageEvent
that emits the current message
when the handleClick()
function gets called from the view
message.component.html
<div>
{{message.value}}
<button (click) = handleClick()>Post message</button>
</div>
This is just a simple view that displays the message value and has a button that calls the handleClick()
function when pressed. It would be better to have an input field, but that is a topic for another day ;)
Now back to the parent component. In order to get the message object, I call the postMessageEvent
through the view like so
post-message.component.html
<div>
...
<!-- other code -->
<message (postMessageEvent)=postMessage($event)></message>
</div>
I use the same event name postMessageEvent
inside the brackets and assign that to a function postMessage()
on the component like
post-message.component.ts
import { Component, OnInit } from "@angular/core";
@Component({
selector: "post-message",
templateUrl: "./post-message.component.html",
styleUrls: ["./post-message.component.css"]
})
export class PostMessageComponent implements OnInit {
constructor() {}
ngOnInit() {}
postMessage(messageFromChild: IMessage) {
console.log(messageFromChild.id);
console.log(messageFromChild.value);
//call service/api to post message
}
}
As we emit the message from the child component, the postMessage
function takes a parameter which is basically the message object from the child. So when you click the button on the child component the postMessage
on the parent component gets fired and you have access to the current message
object And that's all. Now you can use your messageFromChild
to call a service/api or do anything you want.
Posted on October 25, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.