Template Reference Variable in AngularJS
Template Reference Variable in angular is used to access all the properties of any element inside DOM. It can also be a reference to an Angular component or directive or a web component.
Template Reference Variable can refer to the following –
- DOM element
- Angular Component
- Web Component
- Create an Angular app to be used.
- Create the input element and add the template reference to this input field using # tag.
- Bind this template reference inside the button click method “changeTitle()”.
- Now inside the changeTitle method, we have full access to this input field and here we have set the input field value and focus properties.
Syntax : Use # tag before variable name. example – #geek
<input #geek placeholder="" />
In the above HTML template, we have created an input element with the template reference variable “email” and we have created a button. On button click, we access the complete input element and all its properties.
"#geek" is template reference variable on input field
The template reference variable of the input element is accessible inside the changeTitle() function and on the button click, we are updating the input element value and also make this field focussed.
Example 2: In the template-driven forms, we are actually using the template reference variable to access the form data.
So here we are accessing the form data using template reference variable on the form element and on form submit we are displaying the input email provided through the form field.
So the complete form fields are accessed using the “itemForm” template reference variable, and we are displaying the email address in the browser.