Template Reference Variable | Data Binding | Angular 15+
A Template reference variable is a reference to any DOM element, component or a directive in the template. It is a special kind of variable that you can declare in a template using the # symbol.
demo.component.html
when input changed, its value print in <p>
<input type="text" #myVariable (keyup)="0">
<p>{{ myVariable.value }}</p>
use in Elements:
You can use a template reference variable to reference an element in the template and access its properties or methods. For example, if you have an input element, you can define a reference variable for it and use it to access its value:
user.component.html
<input type="text" #myInput>
<button (click)="submit(myInput.value)">Submit</button>
user.component.js
export class UserComponent {
submit(val:string){
console.log(val);
}
}
Components:
<app-child #myChild></app-child>
<button (click)="myChild.doSomething()">Do something</button>
In this example, we have defined a template reference variable myChild for a child component app-child. When the button is clicked, we are calling a method doSomething() on the child component using myChild.doSomething().
Directives:
<div myDirective #myDiv></div>
<button (click)="myDiv.myDirectiveMethod()">Call directive method</button>
In this example, we have defined a template reference variable myDiv for a div element with the myDirective directive. When the button is clicked, we are calling a method myDirectiveMethod() on the directive using myDiv.myDirectiveMethod().