DEV Community

Deepa Chaurasia
Deepa Chaurasia

Posted on

Directive Composition API

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()">

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post