在代码笔示例中,您使用typescript作为预处理器,以便所有代码都由typescript编译。
Angular有内置的DI系统,很大程度上依赖于我们在TS代码的构造函数中提供的类型。
constructor(private element: ElementRef) { }
^^^^^^^^^^^
we have to keep this type after ts compilation
默认情况下,typescript在编译后不保留该信息,但我们可以设置一个名为
emitDecoratorMetadata
为了保持这种类型:
__metadata("design:paramtypes", [ElementRef])
但是codepen似乎没有这样的选择来改变这一点
tsconfig.json
因此,您必须自己将该类型提供给编译后的版本。
以下是几个选项:
1)专用
@Inject
装饰者:
constructor(@Inject(ElementRef) private element: ElementRef) {}
2)静态
parameters
类类型上的属性:
class PointerDirective implements OnInit {
constructor(private element: ElementRef) {}
static parameters = [ ElementRef ]
3)静态
ctorParameters
方法:
class PointerDirective implements OnInit {
constructor(private element: ElementRef) {}
static ctorParameters = () => [{ type: ElementRef }]
Forked Codepen