Angular Template Reference Variable Example

By Arvind Rai, February 12, 2024
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.

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

Find the print-screen of the output.
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







©2024 concretepage.com | Privacy Policy | Contact Us