Favoring Composition Over Inheritance: Angular's Directive Composition API
Host Directives: Assemble reusable component features through composition rather than rigid class inheritance.
Host Directives: Assemble reusable component features through composition rather than rigid class inheritance.
In classic object-oriented code, developers often lean on inheritance (class Button extends BaseButton) to share logic across UI components. In modern frontend systems, however, inheritance quickly creates rigid hierarchies, fragile base classes, and tight coupling. Worse, TypeScript strictly enforces single inheritance—a component can never extend more than one base class.
Introduced in Angular 15 and built for standalone components, the Directive Composition API (hostDirectives) operationalizes a fundamental software design principle: favor composition over inheritance.
Instead of deep class hierarchies or forcing template consumers to manually attach a laundry list of directives, hostDirectives lets you assemble reusable standalone directives directly onto a component's host element like building blocks.
| Strategy | How it Works | The Catch | Class Inheritance (extends BaseWidget) | | --- | --- | --- | --- | | Component inherits from a single base class | Single inheritance only; base constructor changes break subclasses; no direct DOM/template lifecycle hooks. | Directives in Template (<button appTooltip appRipple>) | Consumer manually attaches directives in HTML | | High boilerplate; if an engineer forgets appRipple, the design system becomes inconsistent. | hostDirectives Composition | The component declares applied directives inside @Component | Automatic, encapsulated, and composable. Supports multiple directives with selective input/output exposure. |
Any directive applied as a host directive must be standalone.
// src/app/shared/directives/ripple.directive.ts
import { Directive, ElementRef, HostListener, inject, input } from '@angular/core';
@Directive({
selector: '[appRipple]',
standalone: true
})
export class RippleDirective {
private el = inject(ElementRef);
rippleColor = input('rgba(255, 255, 255, 0.4)');
@HostListener('click', ['$event'])
triggerRipple(event: MouseEvent): void {
const circle = document.createElement('span');
circle.style.backgroundColor = this.rippleColor();
circle.classList.add('ripple-wave');
this.el.nativeElement.appendChild(circle);
setTimeout(() => circle.remove(), 600);
}
}
Add the directive to the hostDirectives array of your component. It binds directly to the component's host tag:
// src/app/ui/primary-button.component.ts
import { Component } from '@angular/core';
import { RippleDirective } from '../shared/directives/ripple.directive';
@Component({
selector: 'app-primary-button',
standalone: true,
// Automatically attaches RippleDirective to <app-primary-button>
hostDirectives: [RippleDirective],
template: `
<button class="btn-primary">
<ng-content />
</button>
`,
styles: [`
:host { display: inline-block; position: relative; overflow: hidden; }
`]
})
export class PrimaryButtonComponent {}
Every time <app-primary-button> is used, ripple behavior is wired up automatically. The consumer doesn't need to remember anything in their template.
By default, all inputs and outputs of a host directive are private to the host component. The consumer using <app-primary-button> cannot see or bind to them.
When the parent needs to configure the underlying directive, expose properties explicitly using object syntax.
import { Component } from '@angular/core';
import { RippleDirective } from '../shared/directives/ripple.directive';
@Component({
selector: 'app-primary-button',
standalone: true,
hostDirectives: [
{
directive: RippleDirective,
// Expose 'rippleColor' on <app-primary-button>
inputs: ['rippleColor']
}
],
template: `<button><ng-content /></button>`
})
export class PrimaryButtonComponent {}
Consumers can now set the property directly on the component:
<app-primary-button [rippleColor]="'rgba(0, 150, 255, 0.3)'">
Click Me
</app-primary-button>
If a directive's input name clashes with an existing component property or doesn't match your design system's conventions, alias it using 'directiveProp: publicAlias':
@Component({
selector: 'app-primary-button',
standalone: true,
hostDirectives: [
{
directive: RippleDirective,
// Maps internal 'rippleColor' to external 'waveColor'
inputs: ['rippleColor: waveColor']
}
],
template: `<button><ng-content /></button>`
})
export class PrimaryButtonComponent {}
<!-- Clean public API for consumers -->
<app-primary-button [waveColor]="'#ff0055'">
Save Changes
</app-primary-button>
With class inheritance, you cannot extend both HasTooltip and HasFocusTrap. With hostDirectives, you can stack multiple behaviors without friction:
// src/app/ui/menu-panel.component.ts
import { Component } from '@angular/core';
import { TooltipDirective } from '../shared/tooltip.directive';
import { FocusTrapDirective } from '../shared/focus-trap.directive';
import { KeyboardNavDirective } from '../shared/keyboard-nav.directive';
@Component({
selector: 'app-menu-panel',
standalone: true,
hostDirectives: [
// 1. Tooltip with an exposed and aliased input
{
directive: TooltipDirective,
inputs: ['tooltipText: panelHint']
},
// 2. Focus trap (internal behavior, zero inputs/outputs exposed)
FocusTrapDirective,
// 3. Keyboard navigation with an exposed event output
{
directive: KeyboardNavDirective,
outputs: ['itemSelected: onNavigate']
}
],
template: `
<nav class="menu-box">
<ng-content />
</nav>
`
})
export class MenuPanelComponent {}
hostDirectives isn't restricted to @Component. Directives can compose other directives to form higher-level "meta-behaviors":
@Directive({ selector: '[appHighlight]', standalone: true })
export class HighlightDirective { /* ... */ }
@Directive({ selector: '[appSelectable]', standalone: true })
export class SelectableDirective { /* ... */ }
// Composite directive combining both behaviors
@Directive({
selector: '[appInteractiveRow]',
standalone: true,
hostDirectives: [
HighlightDirective,
SelectableDirective
]
})
export class InteractiveRowDirective {}
Any component or table row that applies appInteractiveRow gains both highlighting and selection logic automatically.
When the host component needs to interact with an attached directive programmatically, inject it directly using inject():
import { Component, inject, OnInit } from '@angular/core';
import { TooltipDirective } from '../shared/tooltip.directive';
@Component({
selector: 'app-help-icon',
standalone: true,
hostDirectives: [TooltipDirective],
template: `<span>?</span>`
})
export class HelpIconComponent implements OnInit {
// Injects the exact directive instance bound to this component's host
private tooltip = inject(TooltipDirective);
ngOnInit(): void {
this.tooltip.showProgrammatically('Need help? Click for documentation.');
}
}
Understanding execution order keeps host directive interactions predictable:
1. Directive instantiation & DI resolution (Directives construct before the Host Component)
│
2. Directive inputs bound from consumer template
│
3. Directive ngOnInit / ngAfterViewInit runs
│
Here is how hostDirectives separates accessibility and state management from presentation:
// src/app/shared/aria-toggle.directive.ts
import { Directive, HostBinding, model } from '@angular/core';
@Directive({
selector: '[appAriaToggle]',
standalone: true
})
export class AriaToggleDirective {
checked = model(false);
@HostBinding('attr.role') role = 'checkbox';
@HostBinding('attr.tabindex') tabindex = 0;
@HostBinding('attr.aria-checked') get ariaChecked() {
return this.checked();
}
}
// src/app/ui/custom-checkbox.component.ts
import { Component, HostListener, inject } from '@angular/core';
import { AriaToggleDirective } from '../shared/aria-toggle.directive';
@Component({
selector: 'app-custom-checkbox',
standalone: true,
hostDirectives: [
{
directive: AriaToggleDirective,
inputs: ['checked'],
outputs: ['checkedChange']
}
],
template: `
<span class="box" [class.filled]="aria.checked()">
@if (aria.checked()) { ✓ }
</span>
<span class="label"><ng-content /></span>
`,
styles: [`
:host { display: inline-flex; align-items: center; cursor: pointer; gap: 8px; }
.box { width: 18px; height: 18px; border: 2px solid #555; display: grid; place-items: center; }
.box.filled { background-color: #007acc; border-color: #007acc; color: white; }
`]
})
export class CustomCheckboxComponent {
// Inject the directive to read its state inside our template
protected aria = inject(AriaToggleDirective);
@HostListener('click')
@HostListener('keydown.space', ['$event'])
toggle(event?: Event): void {
event?.preventDefault();
this.aria.checked.update(val => !val);
}
}
<!-- Fully accessible checkbox with zero manual ARIA attributes required by the consumer -->
<app-custom-checkbox [(checked)]="newsletterSubscribed">
Subscribe to monthly updates
</app-custom-checkbox>