Angular Q&A: How do Template Ref Variables work?

In Angular, a template reference variable is a reference to a DOM element or directive within a template. It can be used to refer to the element or directive from within the template, and can be used to access the properties and methods of that element or directive.

To use a template reference variable, you first need to add a # character and a name for the variable to a DOM element or directive in your template. For example, if you have a <input> element that you want to reference in your template, you can add a template reference variable like this:

<input #myInput>

Once you have added the template reference variable to an element or directive in your template, you can then use that variable to refer to the element or directive in the rest of your template. For example, you can use the variable to bind to the element's value property, like this:

<input #myInput value="{{myValue}}">

You can also use the variable to call methods on the element or directive. For example, if the element has a focus() method, you can call that method using the template reference variable like this:

<input #myInput>
<button (click)="myInput.focus()">Focus Input</button>

Overall, template reference variables provide a way to refer to elements and directives in a template, and to access their properties and methods. This can be useful when you need to work with the DOM in your Angular application.

💡
Want to sponsor matcha.fyi? You can have your brand featured right here. Let's connect and chat about it.