Call child component methods from Parent Component using Template Reference variable

Call child component methods from Parent Component using Template Reference variable


A parent component cannot invoke child methods or read child properties using data binding but you can do this using the template reference variable for the child component and then reference that variable in the parent component.


Call Child Component methods Angular



Child Component

user-input.component.ts


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

@Component({
  selector: 'app-user-input',
  templateUrl: "./user-input.component.html"

  ,
  styleUrls: ['./user-input.component.css']
})
export class UserInputComponent {

  counter : number  = 0;
  
  IncrementCounter (){
    this.counter++;
  }
  
}


We will access the property "counter" and IncrementCounter() from the child in the parent component.


Parent component

app.component.ts

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

@Component({
  selector: 'app-root',
  template:
  `
  <button (click) = "child.IncrementCounter()" > Click </button> <br/>

  <app-user-input #child></app-user-input>

  Button is cliked {{child.counter}} times.

  `
  ,
  styleUrls: ['./app.component.css']
})

export class AppComponent {

}



We have placed a local variable #child on the child tag in the parent component. You can choose any name for the local variable. Using this local variable you can call any method from the child component and also access its properties.


This local variable #child gives you a reference to the child component. 


Note: With the local template reference variable technique, only the parent template can access the property and methods of the child component, But the Instance of parent component class can not read/write child component properties and can not call the methods also.


















Post a Comment

0 Comments