Search code examples
angulartypescriptangular-directive

Consolidating Two Directives into a Single One


Suppose one has two predefined directives dir1 and dir2 ( which are provided by a 3rd party API that one has no control over). Let's say these can be applies to an html element as follows:

<div dir1="red" [dir2]="123">... My Content ...</div>

I have found myself applying the above the directives with the exact same binding values in several places in my code. Rather than repeat myself, I would like to create my own custom directive, call it myDir, that I could apply like this:

<div MyDir >... My Content ...</div>

This should be exactly the same as applying dir1 and dir2 as in the prior example above i.e. it will have the values "red" and 123 hard coded within it's class.

I have tried setting host bindings as in the following plunker example, but this doesn't work..

One idea I have is if only typescript had multiple inheritance, then I would simply write the MyDir class an extension of Dir1 and Dir2..

My question is how do I go about writing the custom directive (MyDir) to achieve the intended use?

Kindly Assist, Thanks You!

https://plnkr.co/edit/W20Wvew326qsGfPU5H6v


Solution

  • Since Angular 15 you can use Directive composition API. What you're looking for is adding directives to another directive

    Your example will be:

    @Directive({
      hostDirectives: [Dir1, Dir2],
    })
    export class MyDir {
      dir1 = inject(Dir1, { self: true });
    }