Angular – Template Reference Variable

On the last tutorial article, we tackled how routes are created and used. In this article, we will talk about template reference variable.

A template reference variable is a variable that refers to a specific DOM element or a directive within the template. It is usually prefixed by a hashtag(#) symbol or ref- prefix.  

template reference variable

Here are some examples:

template reference variable

  • An input field accepts a text and labels it as #firstName
  • When the button is clicked, it calls the setName() method with the value of #firstName

template reference variable

  • This is the same as the previous example but with using the ref- prefix

template reference variable

  • Here we have a template reference variable called #stockForm
  • You can validate the form by calling the stockForm.form.valid

Going back to the example we created previously, we have a template reference variable named #stockForm.

template reference variable

  • An interpolation is added to check the validity of this stockForm.

Save this and go back to your browser to test.

template reference variable

  • It’s saying false because there are no inputs in either of the fields.

template reference variable

  • Now that the input fields are filled, stockForm validity is now true.

Next we’re going to add a stockName variable that shows the inputed value simultaneously.

template reference variable

Save your work and go back to your browser to see the results.

template reference variable

And that’s what template reference variable is all about. On the next lesson, we will give you an overview on Observables.

Subscribe Now and Upgrade Your Skills Today!
Sign up now and have the latest tech tutorials delivered straight to your mailbox.

PLUS: Get exclusive member-only discounts (up to 80% OFF!!) on our top tech courses in Udemy!
We hate spam. Your email address will not be sold or shared with anyone else.