如何将子类的指令注入到组件中



我有一个组件,它应该根据添加到元素中的指令来更改其行为。此自定义逻辑在指令中定义,因此在添加新的作用域/功能时不需要修改组件。

MyComponent
MyDirectiveBase
MyDirective1 extends MyDirectiveBase
MyDirective2 extends MyDirectiveBase

在组件构造函数中,我希望注入应用于元素的指令。当我知道将要使用的确切类时,我可以毫无问题地做到这一点,但我想要的是从MyDirectiveBase扩展的任何指令。

如何告诉DI框架允许MyDirectiveBase的所有子类

我尝试过使用注入令牌(multi=true(,但这只是给了我一个类/函数数组,而不是元素实例。此外,如果未指定任何属性,则不应注入任何指令。

回购样本: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

这是一个示例。

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

其基本思想是使每个指令为基类MyGreetingDirective提供实现类。因此HelloComopent可以根据您的属性从Angular DI获得不同的指令实例。

最新更新