Sitemap
JavaScript in Plain English

New JavaScript and Web Development content every day. Follow to join our 3.5M+ monthly readers.

Member-only story

Angular Template Variables: A Comprehensive Breakdown

3 min readSep 4, 2024

--

Template variables are a simple way to reference DOM elements or directives inside your template, allowing you to use their values or manipulate them elsewhere in your component.

In this article, we will break down the syntax, scope, and use cases of template variables, demonstrating how they can be used effectively.

Declaring a Template Variable

To declare a template variable in Angular, you use the # symbol, followed by a variable name. You can use this variable to reference DOM elements like inputs, buttons, or even Angular components.

Example:

<input #phone placeholder="Enter your phone number" />

In this case, the #phone variable refers to the <input> element.

Using Template Variables

Once declared, you can use the template variable elsewhere in your template. For example, you can access the value of the input element and pass it to a function when a button is clicked.

Example:

<input #phone placeholder="Enter your phone number" />
<button (click)="callPhone(phone.value)">Call</button>

--

--

JavaScript in Plain English
JavaScript in Plain English

Published in JavaScript in Plain English

New JavaScript and Web Development content every day. Follow to join our 3.5M+ monthly readers.