Angular Template Reference Variables

In the previous article, we learned about Angular style binding. In this article, we’ll learn about Template Reference Variables. It is the reference to any DOM elements.

What is Angular Template Variable?

Sometimes we want to flow some data from the view to the class to operate, which is possible with Angular template variables. For example, we want users to enter their name and display their name with some welcome message on pressing enter. We can achieve these criteria using the Template Reference Variables.

Let’s see the Syntax first to understand it:

<input #inputText type="text" placeholder="Enter your name">
  • Template Reference Variable is declared using # and the variable’s name with it.
  • inputText is the variable that we chose.

Now let’s understand how it works:

<input #inputText type="text" placeholder="Enter your name">
<button (click)="message(inputText.value)">Enter</button>
<h1>{{msg}}</h1>
  • In the above code, we took an input field where the user will input their name.
  • click event will be fired when the user clicks on the Enter
  • message function, defined in the ts file will be called with the input field’s value as an argument.
  • .value is used to get the value of the DOM elements.

Example

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  title = 'my-app';
  msg = ""
  message(value : any){
    this.msg = "Welcome To Errorsea " + value
  }
}

The message function will take the value and display a message with the name of the user.

Output:

angular template reference variable example

This is how the Template Reference Variable works.

Conclusion

We hope this article has cleared your concept on Template Reference Variables and how to deal with them. In the upcoming article, we’ll further proceed to some more important topics of Angular.

Read Next: Angular Two-Way Data Binding

Leave a Reply

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