Tutorial – 15 – Template reference variables

Template reference variables ( #var )

A template reference variable is often a reference to a DOM element within a template. It can also be a reference to an Angular component or directive or a web component.

<input #phone placeholder="phone number">

Example

app.component.ts

import { Component } from '@angular/core';
import {NgForm} from '@angular/forms';

@Component({

selector: 'app-root',
   templateUrl: './app.component.html',
   styleUrls: ['./app.component.css'],
   providers:[]
})

export class AppComponent {
   Name:string;
  
  onSubmit(name) {
      this.Name=name;
  }
}
app.component.html
<form (ngSubmit)="onSubmit(name.value)" #demoForm="ngForm">

<div class="form-group">
    <labelfor="name">Name</label>
    <inputtype="text"class="form-control"name="name"required #name/>
</div>
<buttontype="submit">Submit</button>
</form>
{{Name}}
Output
Keshab
The scope of a reference variable is the entire template. Do not define the same variable name more than once in the same template. The runtime value will be unpredictable.

Leave a Reply

Your email address will not be published. Required fields are marked *