How to communicate between two components in Angular through template reference?

Angular allows component interaction in five ways:

  1. Through @Input annotation , a parent component can pass its values to a child component
  2. Through @Output annotation , a child component can pass its values and event to a parent component
  3. Through services, a child component can subscribe to events of the parent.
  4. Through template reference , a parent can access a child’s properties and methods inside the template.
  5. Through @ViewChild annotation , a parent can access a child’s properties and methods inside the typescript component code.

This post is about how to access a child’s properties and methods using template reference variable.

Lets say a parent wants to poke the child and while doing so a method of the child is invoked and its property accessed by the parent.

First lets consider the child code :

Here is the component code :

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

  name;

  collectName(event:any){

    this.name = event.target.value;
  }

  sayHello(){


    alert("Hello , I am "+this.name);
  }

}

It has one property ‘name”

And one method “sayHello()”

The template code :

<br>
<label>Enter the child's name:</label>
<input  (keyup)="collectName($event)"/>

It just collects a value from input text box and stores it in the property ‘name’.

Now lets consider the parent code.

There is no implementation in the typescript code . Template reference variables is only useful at the template and cannot be accessed in the typescript.

Here is the template code :



<app-child #child></app-child>

<br>

<button (click)="child.sayHello()"> Poke Child</button>

Here the child component is referred to using the template reference “#child”.

This can be then used to access any property or method in the child.

On click of the button the child’s method is invoked.

Here is the output:

The name entered in the textbox of the child component is passed on to the parent.

That’s it!

A very simple way to interact between components.

The drawback of this strategy is that the parent component has no access to the child’s properties and methods, only the template has.

This can be resolved by using @ViewChild annotation.

I will write about it in the next post.

Comments

One response to “How to communicate between two components in Angular through template reference?”

Leave a Reply

Discover more from The Full Stack Developer

Subscribe now to keep reading and get access to the full archive.

Continue reading