DEV Community

Prayatna Bhattarai
Prayatna Bhattarai

Posted on • Updated on

TIL: How to pass data from child to parent component using a template variable

Was trying to look for ways on how to pass data around from a child to a parent component and I found a very easy way - using a template variable.

If you had followed my previous post, I used the postMessage component to post a message that has been used on the child component i.e the message component by using Output(). But I have found a cleaner way.


    .. other stuff
    <message #myMessage></message>
Enter fullscreen mode Exit fullscreen mode

#myMessage is a template variable that you can use on the postMessage component's view. So here, I could access any public field or methods of the message component through the template variable.


import { Component, EventEmitter, OnInit, Output } from "@angular/core";

  selector: "message",
  templateUrl: "./message.component.html",
  styleUrls: ["./message.component.css"]
export class MessageComponent implements OnInit {
  message: IMessage;
  constructor() {}

  ngOnInit() {
    //eg message - would basically come from user input though
    this.message = {
      value: "This is a message I like to post",
      id: 1
Enter fullscreen mode Exit fullscreen mode

So, whatever I assign to this.message will have the value available on the postMessage component which is the parent component of message

Hope that is handy. :D

Top comments (0)