Template Reference Variables
In modern Angular development, Template Reference Variables are a powerful way to "reach out and touch" an element or a component directly within your HTML. Think of them as a way to create a handle or a nickname for an element so you can use its properties elsewhere.
We will explain this using a simple Product Search example.
1. What is a Template Reference Variable?
A template reference variable is a name you give to an element using the hash symbol (#).
- Syntax:
#variableName - Scope: It is available anywhere within the same HTML template.
2. Basic Example: Accessing an HTML Element
Let’s say you have an input field where users type a product name. Instead of using complex data binding, you can use a reference variable to "grab" the value directly.
src/app/search/search.component.html
src/app/search/search.component.ts
Why use this?
In the example above, we didn't need to create a variable in the TypeScript file just to hold the input text. The #productInput variable allowed the button to "peek" inside the input and grab its text instantly.
3. Advanced Example: Accessing a Child Component
You can also place a reference variable on a custom Angular component. This gives you access to that component's Public API (all its public properties and methods).
The Child Component (ProductDetail)
src/app/product-detail/product-detail.component.ts
The Parent Template (ProductList)
Using the # symbol on the child tag allows the parent to control the child directly from the HTML.
src/app/product-list/product-list.component.html
4. Key Takeaways
| Feature | Description |
| Identifier | Always starts with a # (e.g., #myRef). |
| What it refers to | The DOM element or the Component instance it is placed on. |
| Usage | Best for simple UI logic, accessing third-party components, or grabbing input values. |
| Limitation | It is only visible in the HTML template (unless you use @ViewChild in TypeScript). |
When to use this approach?
- Simplicity: When you want to pass an input value to a function without setting up
ngModelor Reactive Forms. - Direct Control: When you need to call a specific method inside a child component (like
play()on a video player component oropen()on a modal).