Sub topic 8
Reading a directive from the template with exportAs
A directive attached to an element often holds state or methods that other parts of the template want to use. A button might need to switch a highlight on, or a label might need to show whether the highlight is active. The exportAs option makes the directive instance available to the template through a template reference variable. This chapter shows how to declare it, use it, and diagnose the errors it produces.
This chapter assumes you can write a standalone attribute directive with @Directive, apply it through a component's imports array, and use signals (signal, input) in TypeScript. It also assumes you know what a template reference variable such as #name is.
The problem: a reference gives you the element
A template reference variable written as #hl on a plain element refers to the DOM element. On a component's tag it refers to the component instance. It never refers to an attribute directive unless you ask for it explicitly.
<p appHighlight #hl>Text</p>
<button (click)="hl.toggle()">Toggle</button>This template fails to compile. hl is the HTMLParagraphElement, and the DOM has no toggle method on a paragraph. The directive instance exists, but nothing in the template names it.
Declaring exportAs
exportAs is a string in the @Directive metadata. It gives the directive instance a name that template reference variables can request.
The directive below is a variant of the highlight directive from earlier chapters. The hover listeners are removed so the template can control the state. Its state and methods are public, because the template reads them.
import { Directive, input, signal } from '@angular/core';
@Directive({
selector: '[appHighlight]',
exportAs: 'appHighlight',
host: {
'[style.backgroundColor]': 'active() ? (color() || "yellow") : null',
},
})
export class HighlightDirective {
color = input('', { alias: 'appHighlight' });
readonly active = signal(false);
toggle() {
this.active.update((value) => !value);
}
on() {
this.active.set(true);
}
off() {
this.active.set(false);
}
}The export name does not have to match the selector. Matching them is a convention, and it makes the name easy to guess. A directive with the selector [appHighlight] almost always uses exportAs: 'appHighlight'.
Using the exported instance
To request the instance, assign the export name to the reference variable: #hl="appHighlight". Angular looks among the directives on that element for one whose exportAs matches, and binds the variable to that instance.
Reading values and calling methods
import { Component } from '@angular/core';
import { HighlightDirective } from './highlight.directive';
@Component({
selector: 'app-demo',
imports: [HighlightDirective],
template: `
<p appHighlight="lightblue" #hl="appHighlight">Controlled from outside.</p>
<button type="button" (click)="hl.toggle()">Toggle</button>
<span>Highlight is {{ hl.active() ? 'on' : 'off' }}</span>
`,
})
export class DemoComponent {}The reference hl is typed as HighlightDirective, so the template type checker validates hl.toggle() and hl.active(). The span re-renders when the signal changes, because the template reads the signal.
The variable can be used anywhere in the same template, including in elements that come before the one that declares it. Two limits apply:
- A reference declared inside an embedded view, such as an
@ifblock or an<ng-template>, is visible only inside that view. - A reference is not visible to other components' templates. A parent cannot read a child template's
#hl.
Reaching the instance from the component class
Sometimes the component class needs the directive, not just the template. viewChild accepts the reference name. When the variable was declared with an export name, the query returns the directive instance.
import { Component, viewChild } from '@angular/core';
import { HighlightDirective } from './highlight.directive';
@Component({
selector: 'app-demo',
imports: [HighlightDirective],
template: `
<p appHighlight #hl="appHighlight">Controlled from the class.</p>
<button type="button" (click)="reset()">Reset</button>
`,
})
export class DemoComponent {
private highlight = viewChild.required<HighlightDirective>('hl');
reset() {
this.highlight().off();
}
}If you leave out the ="appHighlight" part, the same query returns the element reference instead, and the generic type no longer describes what you get. TypeScript will not catch this mismatch, because the generic on viewChild is an assertion.
What a reference resolves to
The right-hand side of the #name declaration decides what the variable holds. Angular follows the steps below.
The same rules in table form:
| Declaration | On a plain element | On a component tag |
|---|---|---|
| `#ref` | The DOM element | The component instance |
| `#ref="name"` | The directive instance with `exportAs: 'name'` | The directive instance with that name, or the component itself if the component declares that `exportAs` |
Components accept exportAs too, since a component is a directive with a template. A component with exportAs: 'card' can be referenced as #c="card", which is useful when the plain #c form is ambiguous.
Several names and several directives
exportAs takes a comma-separated list, so one directive can answer to more than one name. This is useful when you rename a directive but want older templates to keep compiling.
import { Directive, signal } from '@angular/core';
@Directive({
selector: '[appToggle]',
exportAs: 'appToggle, toggle',
})
export class ToggleDirective {
readonly open = signal(false);
flip() {
this.open.update((value) => !value);
}
}<div appToggle #a="appToggle" #b="toggle">
<button type="button" (click)="a.flip()">Flip</button>
<span>{{ b.open() }}</span>
</div>Both variables point to the same instance. Changing the state through a changes what b reads.
An element may carry several directives. Each uses its own export name, so each can be referenced separately:
<input appHighlight #hl="appHighlight" appToggle #t="appToggle" />The export name is looked up among the directives matched on that one element only. Angular does not search parent elements. If two directives on the same element both declare exportAs: 'x', the compiler cannot decide between them, so avoid reusing names.
Deciding what to expose
An exported instance makes the whole public surface of the class part of its template API. Keep that surface deliberate:
- Make methods that templates should call
public, and everything elseprivateorprotected. Template code written in another component's template can reach only public members. - Prefer signals for state that templates read. A signal read in a template is tracked, so the view updates when the value changes. A plain field mutated by the directive may not trigger an update when the change happens outside an Angular event handler.
- Prefer small intent-revealing methods such as
toggle()andoff()over exposing writable state. The template then cannot put the directive in an invalid state. - Do not use
exportAsto pass data from the directive to the component that owns the element. An output is the better tool for that, as the previous chapter showed.exportAssuits the case where a sibling or child in the same template needs to command or observe the directive.
Common errors
The most frequent error is a reference to a name that no directive on the element exports:
<p #hl="appHighlight">Plain paragraph</p>Angular reports NG0301: Export of name 'appHighlight' not found!. Three causes account for nearly every case:
- The element does not carry the directive's attribute, so the directive never matched.
- The directive is missing from the
importsarray of the component whose template contains the reference, so the selector matches nothing. - The name in the template differs from the
exportAsstring, usually by a typo or a changed capitalization. Names are case sensitive.
A second class of problem has no error message at all. Writing #hl instead of #hl="appHighlight" compiles and gives you the DOM element. If you then write hl.nativeElement, nothing complains when hl is a plain element, and you get undefined at run time. Check the right-hand side first when a reference behaves unexpectedly.
A third problem is scope. A reference declared inside an @if block cannot be used by a button outside the block, and the compiler reports an unknown property or reference. Declare the directive on an element outside the block, or move the control inside it.
Exercise
A template contains <div appToggle> and later <button (click)="t.flip()">, where t is declared as #t on the div. The compiler fails on t.flip(). What is wrong, and what is the minimum fix? Assume ToggleDirective already has exportAs: 'appToggle'.
Show answer
Without a value, #t refers to the DOM element, which has no flip method. The fix is to write #t="appToggle" on the div. The directive must also be listed in the component's imports, so the selector matches and the name can be found.
Exercise
You rename HighlightDirective's export from 'highlight' to 'appHighlight', but many templates still use #h="highlight". How can you avoid editing every template, and what happens to a template that uses #h="Highlight"?
Show answer
Declare both names with a comma-separated list: exportAs: 'appHighlight, highlight'. Old and new templates then resolve to the same instance. #h="Highlight" still fails with NG0301, because export names are case sensitive.
Exercise
A parent component needs to call off() on a HighlightDirective that sits in its own template on <p appHighlight #hl="appHighlight">. Write the class member that gives the parent a typed handle to the instance.
Show answer
private highlight = viewChild.required<HighlightDirective>('hl'); The parent then calls this.highlight().off(). Because the reference was declared with an export name, the query returns the directive instance and not the element.