Sub topic 10
Composing directives with hostDirectives
This chapter assumes you can write a standalone attribute directive with inputs, outputs, and host metadata, as covered in the earlier chapters. Here you will see how to attach existing directives to another directive or component, so that behavior is reused by composition.
The problem: reusing behavior without inheritance
Suppose you have HighlightDirective and ClickOutsideDirective, and you want a CardComponent that always behaves like a highlighted element. Without hostDirectives you have three options, and each has a cost:
- Ask every consumer to write
<app-card appHighlight>. Consumers can forget it, and the card's behavior now depends on how it is used. - Copy the highlight logic into the card. The logic is now duplicated and can drift.
- Use class inheritance. TypeScript allows only one base class, and Angular decorator metadata such as
hostand inputs gets awkward to share across a hierarchy.
The hostDirectives property of @Component and @Directive solves this. It lists directives that Angular applies to the host element of your class. The consumer writes only <app-card>, and the highlight directive is attached automatically.
Basic syntax
Take the HighlightDirective from the previous chapters. It is standalone, uses host metadata, and exposes one input with the alias appHighlight:
import { Directive, input, signal } from '@angular/core';
@Directive({
selector: '[appHighlight]',
host: {
'[style.backgroundColor]': 'active() ? (color() || "yellow") : null',
'(mouseenter)': 'active.set(true)',
'(mouseleave)': 'active.set(false)',
},
})
export class HighlightDirective {
color = input('', { alias: 'appHighlight' });
active = signal(false);
}The simplest composition lists the class:
import { Component } from '@angular/core';
import { HighlightDirective } from './highlight.directive';
@Component({
selector: 'app-card',
hostDirectives: [HighlightDirective],
template: `<ng-content />`,
})
export class CardComponent {}Every <app-card> element now gets the hover highlight. Nothing in the consumer's template mentions appHighlight, and the consumer does not need to import HighlightDirective.
Three rules apply to every host directive:
- It must be standalone. Directives declared in an NgModule cannot be used.
- Its selector is ignored. Angular attaches it because you listed it, not because an attribute matched.
- Its inputs and outputs are private by default. The consumer cannot bind to them unless you expose them.
The third rule matters most in practice, so the next section covers it.
Exposing inputs and outputs
With the code above, <app-card appHighlight="lightblue"> does not set the color through the host directive. The card chose not to expose the input, so the binding is not part of the card's public API. This keeps the composing class in control of its own interface.
To expose an input, list it in an object form of the entry:
import { Component } from '@angular/core';
import { HighlightDirective } from './highlight.directive';
@Component({
selector: 'app-card',
hostDirectives: [
{ directive: HighlightDirective, inputs: ['appHighlight: highlight'] },
],
template: `<ng-content />`,
})
export class CardComponent {}The string 'appHighlight: highlight' has the form 'publicNameOnDirective: publicNameOnHost'. The left side is the name the directive publishes, which here is the alias appHighlight, not the class property color. The right side is what the card publishes. If you do not need to rename, write the name once: inputs: ['appHighlight'].
The consumer can now write:
<app-card highlight="lightblue">Hover me</app-card>
<app-card>Default yellow on hover</app-card>Outputs work the same way. Here is a click-outside directive that emits through a signal-style output():
import { Directive, ElementRef, inject, output } from '@angular/core';
@Directive({
selector: '[appClickOutside]',
host: {
'(document:click)': 'onDocumentClick($event)',
},
})
export class ClickOutsideDirective {
private el = inject<ElementRef<HTMLElement>>(ElementRef);
clickOutside = output<MouseEvent>();
onDocumentClick(event: MouseEvent) {
if (!this.el.nativeElement.contains(event.target as Node)) {
this.clickOutside.emit(event);
}
}
}A dropdown component can compose it and expose the output under its own name:
import { Component, signal } from '@angular/core';
import { ClickOutsideDirective } from './click-outside.directive';
@Component({
selector: 'app-dropdown',
hostDirectives: [
{ directive: ClickOutsideDirective, outputs: ['clickOutside: dismiss'] },
],
host: {
'(dismiss)': 'open.set(false)',
},
template: `
<button (click)="open.set(!open())">Menu</button>
@if (open()) {
<ul><ng-content /></ul>
}
`,
})
export class DropdownComponent {
open = signal(false);
}A consumer can write <app-dropdown (dismiss)="log()">, and the dropdown also closes itself because it listens to its own host event. The (dismiss) entry in host is valid because the host directive's output is an event on the same element.
How the pieces fit together
When Angular creates <app-card highlight="lightblue">, it instantiates both the host directive and the card on the same element node. They share one ElementRef, one injector node, and one set of DOM listeners.
Because everything lives on one element, the host class can also reach its host directives through dependency injection:
import { Component, inject } from '@angular/core';
import { HighlightDirective } from './highlight.directive';
@Component({
selector: 'app-card',
hostDirectives: [HighlightDirective],
template: `<ng-content />`,
})
export class CardComponent {
private highlight = inject(HighlightDirective);
isHovered() {
return this.highlight.active();
}
}This is a good use of composition: the card reads the directive's public state instead of tracking mouse events a second time.
Directives that compose directives
hostDirectives is also available on @Directive. This lets you build a bundle that you apply with a single attribute:
import { Directive } from '@angular/core';
import { HighlightDirective } from './highlight.directive';
import { ClickOutsideDirective } from './click-outside.directive';
@Directive({
selector: '[appInteractive]',
hostDirectives: [
{ directive: HighlightDirective, inputs: ['appHighlight: highlight'] },
{ directive: ClickOutsideDirective, outputs: ['clickOutside'] },
],
})
export class InteractiveDirective {}Usage in a standalone component:
import { Component } from '@angular/core';
import { InteractiveDirective } from './interactive.directive';
@Component({
selector: 'app-panel',
imports: [InteractiveDirective],
template: `
<div appInteractive highlight="lightblue" (clickOutside)="closed = true">
Panel
</div>
`,
})
export class PanelComponent {
closed = false;
}Host directives can themselves have host directives. Angular resolves the whole chain and applies each directive once.
Execution order
Order matters when directives depend on each other's state. Angular follows these rules:
- Host directives are instantiated before the class that lists them. If
CardComponentinjectsHighlightDirective, the instance already exists when the card's constructor runs. - Lifecycle hooks of host directives run before the same hook on the host. Their
ngOnInitruns before the card'sngOnInit. - Among several host directives, order follows the array.
- Inputs of host directives are set before the host's own
ngOnInit, so an input read in the host'sngOnInitis already available. - Host bindings from both sides are applied to the same element. If two directives bind the same style or attribute, avoid depending on which one wins.
The last point is the one to be careful about. Two directives that both bind [style.backgroundColor] produce a conflict that is hard to debug. Give each directive its own property, or use a class binding for one of them.
Comparing the options
| Approach | Consumer must know about it | Can share inputs/outputs | Works with multiple behaviors |
|---|---|---|---|
| Template attribute (`<app-card appHighlight>`) | Yes | Yes, directly | Yes |
| Class inheritance | No | Yes, but through the base class | No, only one base class |
| `hostDirectives` | No | Only what you list | Yes |
Use hostDirectives when the behavior is part of what your component or directive is. Use a template attribute when the behavior is optional for the consumer.
Common errors
- Using a non-standalone directive. Angular rejects it at compile time. Make the directive standalone first.
- Binding to an unexposed input. The compiler reports that the property is not a known input of
app-card. Add it toinputsin thehostDirectivesentry. - Using the class property name in the mapping. In
inputs: ['color: highlight']the left side must be the directive's public name. BecauseHighlightDirectivealiases the input toappHighlight, you must write'appHighlight: highlight'. - Applying the same directive twice. If
CardComponentalready hasHighlightDirectiveas a host directive and a consumer also writes<app-card appHighlight>, Angular reports an error because a directive can match an element only once. This is another reason to publish a renamed input likehighlight. - Expecting a host directive's selector to matter. It never matches. Only the list in
hostDirectivescounts.
Testing a composed component
Test the composed behavior through the composing class, because that is what consumers use:
import { Component } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { CardComponent } from './card.component';
@Component({
imports: [CardComponent],
template: `<app-card highlight="lightblue">Text</app-card>`,
})
class TestHostComponent {}
describe('CardComponent host directives', () => {
it('applies the exposed highlight color on hover', () => {
const fixture = TestBed.createComponent(TestHostComponent);
fixture.detectChanges();
const card = fixture.nativeElement.querySelector('app-card') as HTMLElement;
card.dispatchEvent(new Event('mouseenter'));
fixture.detectChanges();
expect(card.style.backgroundColor).toBe('lightblue');
});
});The first detectChanges() call sets the input. After the event, the second call updates the host style binding. You do not import HighlightDirective into the test host, because the card brings it along.
Exercise
A ToolbarButtonComponent should always be highlighted on hover, and its users should be able to choose the color with <app-toolbar-button color="pink">. HighlightDirective publishes its input under the alias appHighlight. Write the hostDirectives entry, and explain why inputs: ['color: color'] would fail.
Show answer
Use hostDirectives: [{ directive: HighlightDirective, inputs: ['appHighlight: color'] }]. The left side of the mapping is the directive's public input name, which is the alias appHighlight. The class property name color is not published, so 'color: color' does not match any input of the directive and fails. The right side, color, is the name consumers use on <app-toolbar-button>.
Exercise
A consumer writes <app-card appHighlight highlight="red"> where CardComponent lists HighlightDirective in hostDirectives. What goes wrong, and how do you avoid it?
Show answer
The directive would match the same element twice, once through the host directive and once through the template attribute, and Angular reports an error because a directive may match an element only once. Avoid it by removing appHighlight from the template and using only the exposed highlight input, since the card already applies the directive.