Hash-Name to Grab a DOM Element or Component
Template Reference Variables
A hash-prefixed name on an element exposes that element or component to the rest of the template.
What you'll learn
- Use a template ref on a native element
- Use a template ref on a component to reach its public API
- Pass template refs to event handlers
Sometimes one element in your template needs to talk to another. Adding
#name to an element creates a template reference variable you can
use anywhere else in the same template.
A Ref on a Native Element
<input #email type="email" placeholder="you@example.com" />
<button (click)="send(email.value)">Send</button> The #email ref is the native HTMLInputElement, so email.value,
email.focus(), and every other DOM API are available.
A Ref on a Component
When you put a ref on a component, the variable is the component instance:
<app-modal #m>...</app-modal>
<button (click)="m.open()">Show modal</button>
<button (click)="m.close()">Hide</button> Anything public on the ModalComponent class is reachable via m.
Passing a Ref to a Handler
You can pass the ref straight into a method:
<form #f>
<input name="name" />
<button (click)="dump(f)">Inspect</button>
</form> dump(form: HTMLFormElement) {
console.log(form.elements);
} Scope
A template ref only exists in the template that declared it. You can’t
read #email from a sibling component or from the parent — for that,
use @ViewChild or viewChild(), which we cover later.
When to Reach for ngModel Instead
If you only want the value, two-way binding with [(ngModel)] (covered
earlier) is usually cleaner. Reach for template refs when you need
imperative access — focusing an input, scrolling into view, calling a
component method.