Angular 2 Template Reference Variable Example
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.
Contents
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>
2. Using ref-
Find the example.
<input type="text" ref-myVar>
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">
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)"> </select>
Template Reference Variable with NgForm
Now we will discuss how to accessNgForm
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> </form>
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
app.component.ts
import {Component} from '@angular/core'; @Component({ selector: 'ref-vars-app', template: ` <data-app> </data-app> <br/><br/> <form-app> </form-app> ` }) export class AppComponent { }
import {Component} from '@angular/core'; @Component({ selector: 'data-app', templateUrl: 'app/data.component.html' }) export class DataComponent { colors = ['RED', 'CYAN', 'BLUE']; getData(mob : number, stat : string, cnt: string) { console.log(mob); console.log(stat); console.log(cnt); } setData(val) { console.log(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> <br/> <br/>{{mobile.placeholder}} <br/>{{mobile.value}} <br/>{{mobile.type}} <br/> <br/>{{state.value}} <br/>{{country.value}} <br/><br/> <select #myColor (change) = "setData(myColor.value)"> <option *ngFor = "let color of colors"> {{color}} </option> </select> <p [style.color] = "myColor.value"> Hello World!</p>
import {Component} from '@angular/core'; import {Person} from './person'; @Component({ 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(this.person.pname); 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> </form>
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'; @NgModule({ imports: [BrowserModule, FormsModule], declarations: [AppComponent, DataComponent, FormComponent], bootstrap: [AppComponent] }) export class AppModule { }
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic'; import {AppModule} from './module'; const platform = platformBrowserDynamic(); platform.bootstrapModule(AppModule);
<html> <head> <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> <script> System.import('myApp').catch(function(err){ console.error(err); }); </script> </head> <body> <ref-vars-app>Please Wait...</ref-vars-app> </body> </html>
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.

2424344 UP India CYAN Form Validated:true Hello Form is being submitted