Template reference variables are a very useful feature of Angular 2+ which allow you to save a reference to a DOM element or Angular Component instance.
To declare a template reference variable, write a hash symbol with a name as an attribute of the element, like so:
<input type="text" #myInput>
Now, you can access the variable anywhere in the template. In the below example, the value of the input element is displayed beside it, and the input DOM element gets passed to the onClick
function.
<input type="text" #myInput> {{ myInput.value }}
<button (click)="onClick(myInput)">Submit</button>
Template reference variables can also be referenced in the Component, using the ViewChild
decorator. In the below example, a reference to the input element will be available in this.myInput
.
import { ViewChild, ElementRef } from '@angular/core';
@ViewChild('myInput') private myInput: ElementRef;
Using a reference variable on a Component will give you a reference to the actual Component instance, giving you access to all of its methods and properties.
<my-component #myComponent></my-component>
Top comments (0)