Home  >  Angular

Angular 2 Template Reference Variable Example

By Arvind Rai, December 07, 2016
On this page we will provide angular 2 template reference variable example. A template reference variable is a reference to a DOM element or directive within a template. Using template reference variable we access the values of DOM element properties. Template reference variable is declared using # and ref- as prefix, for example #myVar and ref-myVar. We should not duplicate template reference variable name because in this way it may give unpredictable value. Here on this page we will provide example of template reference variable for input text box, select box and NgForm directive step by step using TypeScript.

Software Used

Find the software used in our demo.
1. Angular 2.3.0
2. TypeScript 2.0.10
3. Node.js 4.6.0
4. NPM 3.10.8
5. Firefox 50.1.0

Template Reference Variable Syntax

We can use template reference variable by two ways.
1. Using #
Find the example.
<input type="text" #myVar>  
Here myVar will be a template reference variable.
2. Using ref-
Find the example.
<input type="text" ref-myVar>  
Here myVar will be a template reference variable.

Template Reference Variable using Input Text Box

Here we will discuss template reference variable using input text box. Template reference variable is a variable using which we can access DOM properties. In our example we are using following DOM properties of input box.

1. placeholder
2. type
3. value Now find the code snippet.
<input type="text" #mobile placeholder="Enter Mobile Number">  
In the above input text box #mobile is a template reference variable. To fetch DOM properties, we do as follows.
mobile.placeholder : It will give placeholder of our text box if we have specified.
mobile.value : It will give value of our text box.
mobile.type : It will give type of input element. In our example type is text.

Template Reference Variable using Select Box

Here we will discuss template reference variable with select box.
<select #myColor (change) = "setData(myColor.value)">

Look at the code snippet, #myColor is a template reference variable. The selected value of select box can be accessed by myColor.value .

Template Reference Variable with NgForm

Now we will discuss how to access NgForm directive using template reference variable. We are creating a sample form here.
<form (ngSubmit)="onSubmitPersonForm(myForm)" #myForm="ngForm">
    <input name="name" required [(ngModel)]="person.pname">
    <button type="submit" [disabled]="!myForm.form.valid">Submit</button>

ngSubmit : It enables binding angular expressions to onsubmit event of the form. Here on form submit onSubmitPersonForm component method will be called.
ngForm : It is the nestable alias of form directive

Here we are using template reference variable for ngForm as #myForm="ngForm" . Now we can use myForm in place of ngForm such as to check form validity and we can also use it in our angular expressions.

Complete Example using TypeScript

import {Component} from '@angular/core';
    selector: 'ref-vars-app',
    template: `
	            <data-app> </data-app>
		    <form-app> </form-app>
export class AppComponent { }  
import {Component} from '@angular/core';
    selector: 'data-app',
    templateUrl: 'app/data.component.html'
export class DataComponent {
        colors = ['RED', 'CYAN', 'BLUE'];
	getData(mob : number, stat : string, cnt: string) {
	setData(val) {
Mobile Number: <input type="text" #mobile placeholder="Enter Mobile Number"> <br/>
Enter State: <input type="text" ref-state> <br/>
Enter Country: <input type="text" #country> <br/>
<button (click)="getData(mobile.value, state.value, country.value)">Get Data</button>


<select #myColor (change) = "setData(myColor.value)">
	<option *ngFor = "let color of colors">

<p [style.color] = "myColor.value"> Hello World!</p>  
import {Component} from '@angular/core';
import {Person} from './person';
    selector: 'form-app',
    templateUrl: 'app/form.component.html'
export class FormComponent {
        person = new Person();
	onSubmitPersonForm(fm) {
		console.log('Form Validated:'+fm.form.valid);
		console.log('Form is being submitted');
<form (ngSubmit)="onSubmitPersonForm(myForm)" #myForm="ngForm">
    <input name="name" required [(ngModel)]="person.pname">
    <button type="submit" [disabled]="!myForm.form.valid">Submit</button>
export class Person {
        id : number;
	pname : string;
	constructor() {
import {NgModule}       from '@angular/core';
import {BrowserModule}  from '@angular/platform-browser';
import {FormsModule}    from '@angular/forms';
import {AppComponent}   from './app.component';
import {DataComponent}  from './data.component';
import {FormComponent}  from './form.component';
  imports:      [BrowserModule,
  declarations: [AppComponent,
  bootstrap:    [AppComponent]
export class AppModule { } 
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
import {AppModule} from './module';
const platform = platformBrowserDynamic();
    <title>Angular 2 Demo</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="node_modules/core-js/client/shim.min.js"></script>
    <script src="node_modules/zone.js/dist/zone.js"></script>
    <script src="node_modules/reflect-metadata/Reflect.js"></script>
    <script src="node_modules/systemjs/dist/system.src.js"></script>
    <!-- Configure SystemJS -->
    <script src="systemjs.config.js"></script>
      System.import('myApp').catch(function(err){ console.error(err); });
    <ref-vars-app>Please Wait...</ref-vars-app>

Run Application

Find the steps to run the example.
1. Install Node.js and NPM in the system if not already installed. Make sure that Node.js version must be 4.x.x or higher and NPM version must be 3.x.x or higher.
2. Download the source code using download link given below in the example.
3. Go to the root folder of the project using command prompt and run npm install command.
4. Now run npm start command.
5. Now run index.html file. Find the print screen of the output.
Angular 2 Template Reference Variable Example
The output in browser console is as follows.
Form Validated:true 
Form is being submitted 


Angular 2 Template reference variables

Download Source Code


©2021 concretepage.com | Privacy Policy | Contact Us