Angular template reference variable in detail

The angular template reference variable is often a reference to a DOM element or directive within a template so we can access and manipulate it in our component.

When to use viewChild decorator or angular template reference?

The angular template reference variable is simply a named reference to a DOM element within a template. It is similar to the id attribute of an HTML element. We can mark a DOM element with a template reference and then query it inside a class using the ViewChild decorator. We can use template reference either directly in the template or pass argument in method from template to component typescript. If we use template reference with viewChild decorator and then we can directly access elements inside the class of components.

Syntax of angular template reference variable

<input #localReferenceName>
The # symbol in our input tag is a way of declaring local reference and these are known as template reference variables. The input element has an attribute whose name starts with the # character, which is used to define a variable to refer to the element in the template’s data bindings.

You add with a hashtag with the name of your choice, like for example student name in an example below. This reference will hold a reference to this element as the whole HTML element we can access to input by access value property of an element. Once we create reference we can use this reference everywhere in our template but not inside typescript code.

Example of an Angular template reference variable.

We will create a simple example to add a local reference to input and pass the local reference in the method as an argument on a button in the template. Let first create project.
Angular template reference variable example
Local reference show element of input itself
ng new myApp

Edit app.component .html to add template reference on input as

<input type="text" class="form-control" #nameInput>
<button class="btn btn-primary" (click)="onAddName(nameInput)">Add name</button>

In typescript of app.component.ts, we can access input value as

onAddName(nameInput: HTMLInputElement) {
  console.log(nameInput.value);
}

Angular template reference variable can only be accessed inside the template. We can use a template reference variable with @viewChild decorator to reference it and access it directly inside the component typescript file. For more information on the angular template reference variable please check an official document of angular.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top