Angular 10 Tutorial - Template Reference Variables

In this tutorial, we will learn about Template Reference Variables in Angular 10. Angular provides us with a way of capturing a reference to any specific DOM element, component, or directive, which can be used somewhere in our template itself.

Using Template Reference Variables in Angular 10

Let's see how we can use Template Reference Variables in Angular 10. So, switch to the project.

Now, let's open the app.component.html file and here, let's add an input text field:


Enter Name : <input type="text" />

Now, add the identifier to the text field. The identifier name used for the template reference variable should be unique and should not conflict with any other template reference variable. So, just add the reference variable here. For adding a reference variable, we use the # sign. So, just write here #name.


Enter Name : <input type="text" #name />

Now, access the text value using the reference variable. So, here, just create a function and call it from a button:


<button (click)="showName(name.target.value)" >Show</button>

Now, let's create this function. So, go to the app.component.ts file and here, just add the function:


name = '';
showName(name)
{
this.name = name;
}

Now, just display the name in the app.component.html file:


{{name}}

Now, let's check it. So, switch to the browser and enter any name. Now, click on "Show". You can see here the name.

Using Reference Variables with p Tag

Let's use a reference variable with a p tag. Just add the p tag and write some text inside this:


<p>Surfside Media</p>

Now, let's print here this text only using the reference variable. So, just add the reference variable first. So, just type #cname.


{{cname. textContent}}

Alright, now let's check it. And here you can see the paragraph text. So, in this way, you can use Template Reference Variables in Angular 10.