<button id="clickMeExample"></button>
let clickMeExample = document.getElementById("clickMeExample");
name = "Robot 100";
In the Robot component html page, we displayed the name of the robot.
{{ name }}
And in the app component html page, there is the robot component and an empty button.
<app-robot></app-robot>
Now, Let’s say that we want to call the speak method in the robot component every time we click on this button. Here is how we will do it with template reference.
<app-robot #robot></app-robot>
<button (click)="robot.speak('Hello, I am a Robot.')">Push Me!</button>
So now, when we click on the button, it will display “Hello, I am a Robot.” in the browser. Let’s verify that.
As you can see, by using the template reference technique, we can quickly get a reference to an element or component and have direct access to all of its public properties and methods.
<button (click)="onClick(robot)">Push Me!</button>
Go to the app component TypeScript file and define the function. For the parameter, it will be the robot component. In the body of the function, we will get the robot reference and then access the name property. Then we will assign it a new value.
onClick(robot: RobotComponent){
So now, when we click on the button, it will change the name of the robot from Robot 001 to Robot 100. Let’s verify that. Save the project and go to the browser. Click on the button.
Robot 100
As you can see, the name of the robot changed from Robot 001 to Robot 100.
Recap
Let’s take a moment to recap what we have learned.