DEV Community

Prayatna Bhattarai
Prayatna Bhattarai

Posted on • Edited on

TIL: How to pass data from child to parent component in Angular

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);
  }
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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
  }
}
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)