The directive composition API lets you apply directives to a component's host element from within the component TypeScript class.
Adding directives to a component
You apply directives to a component by adding a hostDirectives property to a component's decorator. We call such directives host directives.
In this example, we apply the directive MenuBehavior to the host element of AdminMenu. This works similarly to applying the** MenuBehavior** to the element in a template.
@Component({
selector: 'admin-menu',
template: 'admin-menu.html',
hostDirectives: [MenuBehavior],
})
export class AdminMenu { }
When the framework renders a component, Angular also creates an instance of each host directive. The directives' host bindings apply to the component's host element. By default, host directive inputs and outputs are not exposed as part of the component's public API. See Including inputs and outputs below for more information.
Angular applies host directives statically at compile time. You cannot dynamically add directives at runtime.
Directives used in hostDirectives must be standalone: true.
Angular ignores the selector of directives applied in the hostDirectives property.
Including inputs and outputs
When you apply hostDirectives to your component, the inputs and outputs from the host directives are not included in your component's API by default. You can explicitly include inputs and outputs in your component's API by expanding the entry in hostDirectives:
@Component({
selector: 'admin-menu',
template: 'admin-menu.html',
hostDirectives: [{
directive: MenuBehavior,
inputs: ['menuId'],
outputs: ['menuClosed'],
}],
})
export class AdminMenu { }
By explicitly specifying the inputs and outputs, consumers of the component with hostDirective can bind them in a template:
<admin-menu menuId="top-menu" (menuClosed)="logMenuClosed()">
you can alias inputs and outputs from hostDirective to customize the API of your component:
@Component({
selector: 'admin-menu',
template: 'admin-menu.html',
hostDirectives: [{
directive: MenuBehavior,
inputs: ['menuId: id'],
outputs: ['menuClosed: closed'],
}],
})
export class AdminMenu { }
<admin-menu id="top-menu" (closed)="logMenuClosed()">
Top comments (0)