Syntax for Declaring Template Variables

In the template, we use hash symbol (#) to declare the template variable. In the below syntax we’ve declared a template variable called “templateVarName” for the input element. Then the button element is referring to this variable and passes its value to the handleSubmit() method.

<input #templateVarName />
<button type="button" (click)="handleSubmit(templateVarName.value)">Submit</button>

Understanding Templates Variable in Angular

Template variables in Angular allow us to use the data from one part of the template to another part of the same template. There are various use cases where these template variables come in handy. For example, responding to the user input or responding to the form submission.

In this article, we’ll explore what are template variables and how to use them.

Table of Content

  • What are Template Variables?
  • Syntax for Declaring Template Variables
  • Scope of Template Variables
  • DOM Element Template Variable
  • Using NgForm with template Variables

Similar Reads

What are Template Variables?

As we’ve seen in the description itself, by using template variables we can use data from one part of the template to another part of the same template. Now let’s see the places in the template where template variables can be used....

Syntax for Declaring Template Variables

In the template, we use hash symbol (#) to declare the template variable. In the below syntax we’ve declared a template variable called “templateVarName” for the input element. Then the button element is referring to this variable and passes its value to the handleSubmit() method....

Scope of Template Variables

Just like any other local variable, these template variables are also locally scoped to the templates. In other words, we cannot access the value of the template variable outside the template. Therefore it is not possible to use the value of a template variables in the component code directly. To use the value of the template variable in the component code we pass it as an argument to the function from template itself....

DOM Element Template Variable

In this example, we’ll create a template variable called “ageField” for the input element. Then we’ll create a button element that will refer this template variable to display the message....

Using NgForm with template Variables

Let’s consider an example where we’ll create a template variable called “userForm” referring to the Angular’s NgForm directive instance. We’ll check the validity of the form and then display a message accordingly....

Contact Us