Search code examples
angularangular-directiveangular-dependency-injection

How to inject directive of subclass into component


I have a component that should change its behavior depending on what directive is added to the element. This custom logic are defined in the directives so the component needs not be modified when a new scope/feature is added.

MyComponent
MyDirectiveBase
MyDirective1 extends MyDirectiveBase
MyDirective2 extends MyDirectiveBase

In the component constructor, I want to inject the directive that is applied to the element. I can do this without issue when I know the exact class that will be used, but what I want is any directive that extends from MyDirectiveBase.

How can I tell the DI-framework to allow all subclasses of MyDirectiveBase?

I have tried using an injection token (with multi=true), but that just gave me an array of the classes/functions, not the element instance. Also if no attribute is specified, no directive should be injected.

Sample repo: https://github.com/ulvesked/angular-dependency-inject-directive-subclass-to-component

StackBlitz: https://stackblitz.com/edit/angular-ivy-bihzjv?devtoolsheight=33&file=src/app/app.component.html


Solution

  • Here is the a sample.

    https://stackblitz.com/edit/angular-ivy-tnb5up

    The basic idea is make each directive to provide the basic class MyGreetingDirective with implemented class. So HelloComopnent can get different directive instance from Angular DI according to your attribute.