Angular Template Reference Variables – An Explainer #angular #interviewtips

Posted by

What is a template reference variable in Angular?

What is a template reference variable in Angular?

Template reference variables are a way to get a reference to an element in your Angular template. They allow you to access the element and its properties in your component code. You can create a template reference variable by adding a hash symbol (#) followed by the variable name to an HTML element in your template.

For example, if you have an input element in your template, you can create a template reference variable for it like this:

Once you have created the template reference variable, you can use it to access the input element in your component code. For example, you can access the value of the input element like this:


@ViewChild('inputVar') inputElement: ElementRef;
console.log(this.inputElement.nativeElement.value);

Template reference variables are commonly used to access form controls, but they can be used with any HTML element in your template. They are especially useful when you need to access an element in your template from your component code, for example in event handlers or when working with forms.

Template reference variables are a powerful feature of Angular that allows you to easily get a reference to elements in your template and interact with them in your component code.