Handle Template Reference Variables with Directives

Part 5 of Advanced Angular Component Patterns

Isaac Mann
Angular In Depth
2 min readFeb 8, 2018

--

Photo by Samuel Zeller on Unsplash

AngularInDepth is moving away from Medium. More recent articles are hosted on the new platform inDepth.dev. Thanks for being part of indepth movement!

04 Avoid Namespace Clashes with Directives
06 Use <ng-template>

I’ve been using template reference variables pretty liberally in my examples so far, and it’s high time I dive in a bit into how to use them to reference specific directives.

Goal:

Get a reference to a directive from within the template.

Implementation:

A template reference variable is a way of capturing a reference to a specific element, component or directive so that it can be used somewhere else in the same template. They are declared like this#baseToggle or this #myToggle="toggle". Once declared, they can be used anywhere in the template. (Note that if you use an <ng-template> or a structural directive like *ngIf or *ngFor it creates a new template scope and template reference variables declared inside will not be available for use outside.)

Template reference variables will resolve in this order:
1. A directive or component specifically referenced by its exportAs property like this: #myToggle="toggle".
2. The component attached to the element, if present. <toggle-on #toggleOn></toggle-on>
3. The html element, if no component is present. <div #someDiv></div>

1. Directive with exportAs

A directive can have an exportAs property applied to its metadata to allow that directive to be specifically targeted by a template reference variable.

// toggle.directive.ts@Directive({
selector: '[toggle]',
exportAs: 'toggle',
})
export class ToggleDirective { ... }

// app.component.html
<div toggle #myTemplateRefVar="toggle"></div>
// myTemplateRefVar is the ToggleDirective

2. Component

There can only ever be one component per html element. If there is a component attached to that element, then a plain template reference variable will resolve to that component.

// app.component.html<toggle-on #toggleOn></toggle-on>
// toggleOn is the ToggleOnComponent

3. HTML Element

If there is no component attached to that element, the template reference variable will fall back to the element itself.

// app.component.html<div #someDiv></div>// someDiv is an HTMLDivElement

Outcome:

Note: In this stackblitz I print the class name of the template reference variables using constructor.name to make it clear to what each variable refers.

--

--