DEV Community

Austin Spivey for Wia

Posted on

2 2

Template Reference Variables in Angular 2+

Template reference variables are a very useful feature of Angular 2+ which allow you to save a reference to a DOM element or Angular Component instance.

To declare a template reference variable, write a hash symbol with a name as an attribute of the element, like so:

<input type="text" #myInput>

Now, you can access the variable anywhere in the template. In the below example, the value of the input element is displayed beside it, and the input DOM element gets passed to the onClick function.

<input type="text" #myInput> {{ myInput.value }}
<button (click)="onClick(myInput)">Submit</button>
Enter fullscreen mode Exit fullscreen mode

Template reference variables can also be referenced in the Component, using the ViewChild decorator. In the below example, a reference to the input element will be available in this.myInput.

import { ViewChild, ElementRef } from '@angular/core';

@ViewChild('myInput') private myInput: ElementRef;
Enter fullscreen mode Exit fullscreen mode

Using a reference variable on a Component will give you a reference to the actual Component instance, giving you access to all of its methods and properties.

<my-component #myComponent></my-component>

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay