Using LocalReference (Template Reference)

  • Instead of two-way binding, we can easily fetch a value of any input through local references in Angular
  • Lets create a demo project to see an example of it.

First create a demo project in angular using angular CLI

Make changes in the app.component.html file as below :

    <label>Enter text here</label>
    <input type="text"#textBoxRef>
    <button (click)="onButtonClick(textBoxRef)">Click Me</button>
    <p>The text entered in the text box is {{msg}}</p>
    <!--<p>{{textBoxRef.value}} will also provide the same value</p> -->

Make below changes into the app.component.ts file.

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'LocalReferenceDemo';
  msg: string;
  onButtonClick(textBox : HTMLInputElement){
    this.msg = textBox.value;
  }
}

Ouput will some like this :

Reference :

Leave a Comment