Sub topic 3
Reading a Directive with `exportAs`
Assume you know TypeScript classes, Angular templates, standalone components, dependency injection, and basic property and event binding. This chapter focuses on directive instances that a template can read.
Reading a directive from the template with `exportAs`
exportAs gives a directive instance a template variable name. The template can then call its methods or read its properties.
import { Directive, signal } from '@angular/core';
@Directive({
selector: '[appToggle]',
exportAs: 'toggle',
})
export class ToggleDirective {
open = signal(false);
toggle() {
this.open.update(value => !value);
}
}A standalone component imports the directive and assigns it to a local variable:
import { Component } from '@angular/core';
import { ToggleDirective } from './toggle.directive';
@Component({
selector: 'app-menu',
imports: [ToggleDirective],
template: `
<button #menu="toggle" (click)="menu.toggle()">
{{ menu.open() ? 'Close' : 'Open' }}
</button>
`,
})
export class MenuComponent {}The #menu variable refers to the directive instance, not the button element.
Injecting services and cleaning up
Directives can inject services just like components. If a directive creates a subscription, timer, or other resource, connect cleanup to its destruction.
import { Directive, DestroyRef, inject } from '@angular/core';
import { interval } from 'rxjs';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
@Directive({
selector: '[appClock]',
})
export class ClockDirective {
private destroyRef = inject(DestroyRef);
constructor() {
interval(1000)
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe(value => console.log(value));
}
}Composing behavior with `hostDirectives`
hostDirectives attaches an existing directive to a component's host element. This reuses behavior without duplicating implementation.
@Component({
selector: 'app-card',
hostDirectives: [
{ directive: HighlightDirective, inputs: ['appHighlight: highlight'] },
],
template: `<ng-content />`,
})
export class CardComponent {}The component can expose selected directive inputs or outputs under public names.
Testing a directive with a host component
Test the directive through a small host component. This verifies its real template usage.
@Component({
imports: [ToggleDirective],
template: `<button #t="toggle" appToggle (click)="t.toggle()"></button>`,
})
class TestHost {}
it('toggles through exportAs', () => {
const fixture = TestBed.createComponent(TestHost);
const button = fixture.nativeElement.querySelector('button');
button.click();
fixture.detectChanges();
expect(fixture.componentInstance).toBeTruthy();
});Common pitfalls and best practices
- Import a standalone directive wherever its selector is used.
- Use
Renderer2or host bindings instead of unnecessary direct DOM writes. - Avoid browser-only APIs when server-side rendering may run the directive.
- Choose specific selector names to reduce collisions.
- Clean up subscriptions and listeners with
DestroyRef. - Test behavior through a host component instead of testing private fields.
Exercise
What does #control="toggle" refer to when appToggle declares exportAs: 'toggle'?
Show answer
It refers to the ToggleDirective instance attached to that element.