loading...

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

prayatna profile image Prayatna Bhattarai ・1 min read

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.

post-message.component.html

<div>
    .. other stuff
    <message #myMessage></message>
  <div>{{myMessage.message.value}}</div>
</div>
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.

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

Discussion

pic
Editor guide