Back to all posts

Template variables in Angular


Template variables in angular are a powerfull feature that allow developers to ference DOM elements, coomponents or directive direactly with the template.

What are Template Variables?

Template variable are declared using the hash (#) symbol followed by a variable name. For example: #textInput this will enable you to access and manipulate elements or components within the same template.

Declaring Template Variables

<input #myInput placeholder="Enter text">
<button (click)="handleClick(myInput.value)">Submit</button>

In this example, #myInput is a template variable that references the input element, allowing you to access its value when the button is clicked.

Scope of Template Variables

Template variables are locally scoped to the template where they are declared. This means they cannot be accessed outside of that specific template context, ensuring encapsulation.

Example of Using Template Variables

Here’s a simple example demonstrating how to use a template variable with an Angular component:

<!-- app.component.html -->
<h2>Enter Your Name</h2>
<input #nameInput placeholder="Name">
<button (click)="greet(nameInput.value)">Greet</button>

And in the component:

// app.component.ts
export class AppComponent {
  greet(name: string) {
    alert(`Hello, ${name}!`);
  }
}