Angular directive composition

Let’s take a look at one of the most awaited Angular features.

Kevin Kreuzer
7 min readNov 2, 2022

--

Angular 15 is on the horizon, and with it, many great features. One I am incredibly excited about is directive composition.

And I am not the only one. The directive composition has been one of the most upvoted Angular issues on GitHub. Let's see what it's all about.

To explain directive composition, we will look at an actual use case in the form of a digital pinboard. We want to implement a pinboard that displays pins. Each pin should display an info text as a tooltip on hover. Furthermore, each pin can be dragged and dropped and initially rotated.

Digital pinboard with a couple of displayed pins

The code for such an application might look something like this.

<pinboard>
<pin image="rocket"></pin>
<pin image="beer"></pin>
<pin image="keyboard"></pin>
<pin image="testing"></pin>
<pin image="coffee"></pin>
</pinboard>

We have a Pinboard component and project a bunch of pins to it. At this point, our pins will be displayed as illustrated on the graphic on top. This means they aren't yet initially rotated, nor are they draggable, nor will we display a tooltip. All features mentioned on top are missing.

Of course, we could go ahead and implement those features right in the pin component. But luckily, our code base already contains some handy directives with the desired functionality.

There's a DragableDirective, a RotateDirective and a TooltipDirective at our disposal. Let's use those attribute directives to add the missing features to our pins.

<pinboard #dragZone>
<pin rotate="45deg" tooltip="Ship new products" dragable [dragzone]="pinboard"
image="rocket"
></pin>
<pin rotate="-20deg" tooltip="A good beer after a day of coding" dragable [dragzone]="pinboard"
image="beer"
></pin>

<pin rotate="0deg" tooltip="My favourite Keyboard, the Moonlander" dragable [dragzone]="pinboard"
image="keyboard"
></pin>

<pin rotate="10deg" tooltip="Write tests for better code" dragable [dragzone]="pinboard"…

--

--

Kevin Kreuzer

Passionate freelance frontend engineer. ❤️ Always eager to learn, share and expand knowledge.