Using Local References in Angular 4 Templates

In this section, we will talk about template reference. Now, in the Movies.Component.html file, we are already using ngModel and that is fine as we can get data via this way as well. Local reference is the way to get any HTML template access. Now, this variable will hold reference to this HTML element.

Also, as you can see that we can pass this variable to the method as well. In a nutshell, we can use this template variable anywhere inside the template but not in the typescript code. Similarly, my component code looks like

With the above change in place, when I enter movie and see console logs, it will come something like below.

Now, when I click on Add Movie. It will show like

Therefore, this is the element we got here. This is what the local reference gave us. Now, here, we can also get value from that. Below, I have pasted the modified snippet, where I grabbed value out of template variable.

With the above change in place, it will appear like

Therefore, template variable is really nice and powerful way of getting access to the HTML elements and utilize the same in typescript code or same can be utilized in HTML markup as well. Now, we can also get DOM access via these template references. In order to gain the access, we can use @ViewChild() decorator. Below is the sample snippet for the same.

Here, I am accessing the DOM via template variable using @ViewChild() decorator. With the above change in place, when I go ahead and run the same, it will print below output.

Here, if you see closely this HTML element is of type ElementRef which means we can apply this type in our ViewChild variable like shown below.

This also means, that I have to import ElementRef as well. Now, ElementRef has one property called nativeElement as shown below.

This also means that, I can access value of the element via native element like shown below.   With the above change in place, when I add movie, this will print the movie name.

However, one point of caution, we should not assign any value ourselves to native element like shown below.

This is something which is not recommended. There are better ways of doing data-binding and string interpolation. We will cover the same in comins sections. But, just have this in mind, not to update DOM this way. Therefore, when I click on Add Movie, even I don’t have any thing in Movie field, it will print Titanic there.

Download Code:-

Rahul Sahay
Happy Coding