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
- Syntax:
html
<input #usernameInput type="text">
<button (click)="logValue(usernameInput.value)">Show</button>#usernameInputis a local variable referencing the<input>.- It can be used to access
value,checked, and other properties of the element.
- Can reference child components or directives:
html
<child-component #childRef></child-component>
<button (click)="childRef.doSomething()">Call method</button>#childRefreferences an instance of thechild-component.- Allows calling methods and accessing the component's public properties.
- 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 readyPremium
A concise answer to help you respond confidently on this topic during an interview.