Angular Input Output Parameters

Parent Child Component

Call child component methods and properties using template reference variable

Summary : There are 2 ways to pass data from Child Component to Parent Component

  • Output Properties
  • Template Reference Variable

With Output properties there are several moving parts. In the child component we need to create a custom event. Raise the custom event. From the parent component bind to the child component event and handle it.

With the template reference variable approach, we do not have so many moving parts. We just declare a template reference variable and use it to call the child component public properties and methods.

Code Explanation :

#childComponent is the template reference variable to the child component. Using this template variable we can call child component public property (employee) and method (getNameAndGender())

. Using the template reference variable we are calling the child component method getNameAndGender(). The value this method returns is assigned to the innerHTML property of the

element. #h1Variable is the template reference variable for

element.

At this point when you click on an employee panel, you will see that employee’s name and gender displayed by the

element.

Calling the child component property using template reference variable :

Notice in the example below, we are calling the child component public property employee using the template reference variable childComponent.


<h1 #h1Variable></h1>

<div *ngFor="let employee of employees">
  <div (click)="h1Variable.innerHTML = childComponent.employee.name + ' ' + childComponent.employee.gender">
    <app-employee-display [employee]="employee" #childComponent>
    </app-employee-display>
  </div>
</div>

Even now, when you click on an employee panel, you will see that employee’s name and gender displayed by the

element exactly the same way as before.

Leave a Reply

Your email address will not be published. Required fields are marked *