DEV Community

Cover image for Angular 15: Using The Directive Composition API
Henrique Custódia
Henrique Custódia

Posted on • Originally published at henriquecustodia.dev

Angular 15: Using The Directive Composition API

Angular v15 will be released pretty soon, and it's coming with a very nice feature called Directive Composition API.

But, what is it? 🤔

The Directive Composition API allows us to compose directives into components and other directives.

This API works only with standalone components (and standalone directives). As the 14 version added the standalone property, the 15 version added a hostDirectives property.

Let's see how to use this property.

The example below shows a directive called BoxDirective, that sets some styles to the AppComponent using the Composition API:

The result will be:

We can use this new API to reuse a lot of code. It's amazing.

Exposing the directive's input

When adding Inputs and Outputs to a directive, we need to expose those to the component to be able to use them. There are the input and output in the hostDirectives property because of it.

The following example adds an Input property to the BoxDirective.

And we'll add the color input to the inputs array to expose it to the component.

That way we can set a color to the BoxDirective

The result will be:

It's possible to rename the exposed input's name - generally useful when we have directives' inputs with the same name.

Using the renamed property:

Exposing the directive's output

To expose outputs as easily as with inputs. But there's a property called outputs specifically for it.

Using it

In the same way as inputs, it's possible to rename the output's name.

Bonus: OnDestroyDirective 💎

Let's create a reusable directive to destroy old subscriptions.

The following code creates a timer component that uses an interval operator to log an incremental number every second. To avoid memory leaks, it's a good practice to remove observable subscriptions when a component has been destroyed. The OnDestroyDirective will remove the interval subscription automatically after the timer component is destroyed.

The result will be:

👨‍💻

You can check out the code of this post here.

That's all!

I've spent some time writing this post, then, I hope that you enjoyed it!

If you liked it, give some claps/likes to this post or share it with your friends!

Thank you for the reading. 😄

See you! 👋🏼

Top comments (1)

Collapse
 
tojacob profile image
Jacob Samuel G.

Angular continues to add value 🔥