Home  >  Angular

Angular Template Reference Variable Example

By Arvind Rai, October 04, 2021
On this page we will learn Angular template reference variable with examples. A template reference variable is a reference to a DOM element or directive within a template. Using template reference variable, we can 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 names because in this case it may give unpredictable values.
Here on this page we will provide template reference variable examples for input text box, select box and NgForm directive.



Technologies Used

Find the technologies being used in our example.
1. Angular 12.1.0
2. Node.js 12.14.1
3. NPM 7.20.3

Syntax

We can use template reference variable by two ways.
1. Using #
Find the example.
<input type="text" #myVar>  
Here myVar is a template reference variable.
2. Using ref-
Find the example.
<input type="text" ref-myVar>  
Here myVar is a 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 accessing 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.

Using Select Box

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

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

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>
</form>  

ngSubmit : It enables binding angular expressions to onsubmit event of the form. 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 to submit form data and to check form validity.


Complete Example

app.component.ts
import { Component } from '@angular/core';
@Component({
	selector: 'app-root',
	template: `
	            <data-app> </data-app>
		    <br/><br/>
		    <form-app> </form-app>
	          `
})
export class AppComponent { }  
data.component.ts
import { Component } from '@angular/core';
@Component({
	selector: 'data-app',
	templateUrl: './data.component.html'
})
export class DataComponent {
	colors = ['RED', 'CYAN', 'BLUE'];
	getData(mob: string, stat: string, cnt: string) {
		console.log(mob);
		console.log(stat);
		console.log(cnt);
	}
	setData(val: string) {
		console.log(val);
	}
} 
data.component.html
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>  
form.component.ts
import { Component } from '@angular/core';
import { Person } from './person';
@Component({
	selector: 'form-app',
	templateUrl: './form.component.html'
})
export class FormComponent {
	person = {} as Person;
	onSubmitPersonForm(fm: any) {
		console.log('Form Validated:' + fm.form.valid);
		console.log(this.person.pname);
		console.log('Form is being submitted');
	}
} 
form.component.html
<form (ngSubmit)="onSubmitPersonForm(myForm)" #myForm="ngForm">
    <input name="name" required [(ngModel)]="person.pname">
    <button type="submit" [disabled]="!myForm.form.valid">Submit</button>
</form> 
person.ts
export interface Person {
    id : number;
    pname : string;
} 
app.module.ts
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 { } 

Run Application

To run the demo application, find the following steps.
1. Download source code using download link given below on this page.
2. Use downloaded src in your angular CLI application. To install angular CLI, find the link.
3. Run ng serve using command prompt.
4. Now access the URL http://localhost:4200
Angular Template Reference Variable Example
Browser console output.
2424344 
UP  
India 
CYAN 
Form Validated:true 
Hello 
Form is being submitted 

Reference

Template syntax

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI











©2021 concretepage.com | Privacy Policy | Contact Us