Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

  1. Home
  2. Angular Dictionary
  3. Template Variable

Template Variable

Since: Angular 14(2022)

Template Variables in Angular are a syntax that uses the #variableName notation in HTML templates to obtain references to DOM elements or component instances. The obtained references can be used from anywhere within the same template and are useful for retrieving form values and calling child component methods.

Syntax

<!-- Basic syntax: define a variable name with # prefix -->
<elementName #variableName></elementName>

<!-- When specifying the reference target explicitly: specify the name published with exportAs -->
<elementName #variableName="exportAsName"></elementName>

<!-- Can be referenced directly within the same template -->
<button (click)="variableName.method()">Execute</button>
{{ variableName.property }}

Usage Overview

NotationDescription
#variableName (HTML element)Obtains a reference to the DOM object (HTMLElement) of an HTML element.
#variableName (component)Obtains a reference to the child component's instance.
#variableName="ngModel"Obtains a reference to the NgModel directive instance to access form state (valid, dirty, etc.).
#variableName="ngForm"Obtains a reference to the NgForm directive instance to access the entire form's validation state.
@ViewChild('variableName')Retrieves the template variable from the component class side.

Sample Code

An example of using template variables to retrieve an input field's value and call a child component's method.

// app.component.ts
// A sample demonstrating the basic usage of template variables (#variableName).

import { Component, ViewChild, ElementRef } from '@angular/core';
import { FormsModule } from '@angular/forms';

@Component({
  standalone: true,
  imports: [FormsModule],
  selector: 'app-root',
  template: `
    <h2>Reference to DOM element</h2>

    <!-- #inputRef makes this input element's DOM object referenceable -->
    <input #inputRef type="text" placeholder="Enter text">

    <!-- On button click, the value is obtained directly via inputRef.value -->
    <button (click)="showValue(inputRef.value)">Show value</button>
    <p>Input value: {{ displayValue }}</p>

    <hr>

    <h2>NgModel state reference</h2>

    <!-- #emailRef="ngModel" obtains a reference to the NgModel directive -->
    <input
      #emailRef="ngModel"
      [(ngModel)]="email"
      name="email"
      type="email"
      required
      placeholder="Enter email address"
    >

    <!-- emailRef.invalid lets you check the validation result -->
    <p *ngIf="emailRef.invalid && emailRef.touched" style="color: red;">
      Please enter a valid email address.
    </p>
    <p>Validation result: {{ emailRef.valid ? 'Valid' : 'Invalid' }}</p>

    <hr>

    <h2>Entire form state reference</h2>

    <!-- #myForm="ngForm" references the entire form's NgForm instance -->
    <form #myForm="ngForm" (ngSubmit)="onSubmit(myForm)">
      <input
        name="username"
        ngModel
        required
        placeholder="Username (required)"
      >
      <!-- Disable the submit button when myForm.invalid is true -->
      <button type="submit" [disabled]="myForm.invalid">Submit</button>
    </form>
    <p>Form state: {{ myForm.valid ? 'Complete' : 'Incomplete' }}</p>
  `,
})
export class AppComponent {
  displayValue: string = '';

  email: string = '';

  showValue(value: string): void {
    this.displayValue = value;
  }

  onSubmit(form: any): void {
    console.log('Submitted data:', form.value);
  }
}

Overview

Template variables declare a reference to an HTML element or directive using the #variableName form, and can be used directly from event bindings and interpolation bindings within the same template. When attached to an HTML element, the reference target is that DOM object (such as HTMLInputElement); when attached to a component, the reference target is the component's instance.

When used with forms, explicitly specifying the exportAs name as in #variableName="ngModel" or #variableName="ngForm" lets you obtain NgModel or NgForm instances. This allows you to directly reference validation state in the template using properties like variableName.valid and variableName.touched.

To reference template variables from the component class, use the @ViewChild('variableName') decorator. For details, see @ContentChild / @ViewChild. For forms, which are often used in combination with template variables, see Template-Driven Forms.

If you find any errors or copyright issues, please .