Skip to main content

What is a template variable (#var)?

In Angular, a template variable (#var) is a way to create a local reference to a DOM element or a component inside a template, to use its properties and methods without passing data into the component.

Main points

  1. Syntax:
html
<input #usernameInput type="text"> <button (click)="logValue(usernameInput.value)">Show</button>
  • #usernameInput is a local variable referencing the <input>.
  • It can be used to access value, checked, and other properties of the element.
  1. Can reference child components or directives:
html
<child-component #childRef></child-component> <button (click)="childRef.doSomething()">Call method</button>
  • #childRef references an instance of the child-component.
  • Allows calling methods and accessing the component's public properties.
  1. Scope:
  • A template variable is visible only within the current template where it is declared.
  • Not accessible directly in the component's TypeScript code (for that, there is @ViewChild).

In other words, #var is a local reference to an element or component inside the template for direct interaction with it.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.