如何在CodePen上向Angular7应用程序添加指令
我正在学习angular,我正在学习Udemy和检查文档的教程。我是我创造的 现在我试图定义指令,但出现错误: 未捕获错误:无法解析PointerDirective的所有参数: (?) 我的代码如下所示:如何在CodePen上向Angular7应用程序添加指令,angular,typescript,dependency-injection,codepen,Angular,Typescript,Dependency Injection,Codepen,我正在学习angular,我正在学习Udemy和检查文档的教程。我是我创造的 现在我试图定义指令,但出现错误: 未捕获错误:无法解析PointerDirective的所有参数: (?) 我的代码如下所示: @Directive({ selector: '[pointer]' }) class PointerDirective implements OnInit { constructor(private element: ElementRef) { } ngOnInit(
@Directive({
selector: '[pointer]'
})
class PointerDirective implements OnInit {
constructor(private element: ElementRef) { }
ngOnInit() { }
}
@NgModule({
imports: [
BrowserModule,
CommonModule
],
declarations: [ PointerDirective, AppComponent ],
providers: [],
bootstrap: [ AppComponent ]
})
class AppModule {}
我也尝试了不同的名称(应用程序指针),但得到了相同的错误
这支笔是根据这支笔设计的,但在这里它也不起作用
搜索这个错误,我得到的信息是,这可能是循环依赖,但这里我只是有一个简单的指令。怎么了
编辑:
根据@trichetriche,代码只在CodePen上不起作用,我是否遗漏了一些文件?如何在不使用构建过程的情况下,仅使用脚本标记创建基本角度项目?如何使Angular应用程序在Codepen中工作
EDIT2:
所以我想出来了:
@Directive({
selector: '[pointer]'
})
class PointerDirective implements OnInit {
constructor(@Inject(ElementRef) private element: ElementRef) {
}
ngOnInit() { }
}
如果您知道为什么在CodePen上需要
@Inject
,而在普通项目上不需要,请添加答案。在CodePen示例中,您使用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) 类类型上的静态参数属性:
class PointerDirective implements OnInit {
constructor(private element: ElementRef) {}
static parameters = [ ElementRef ]
3) 静态<代码>参数代码>方法:
class PointerDirective implements OnInit {
constructor(private element: ElementRef) {}
static ctorParameters = () => [{ type: ElementRef }]
。问题可能与您的项目有关。你能在一个新项目或stackblitz中复制它吗?@trichetriche感谢或测试,我已经编辑了这个问题。你为什么要强制使用codepen?这个问题似乎与您的项目有关,只需更改它?@trichetriche如果代码使用的是compile,那么出于其他原因,我不需要它,而不是codepen。如果我要删除代码笔限制,我需要删除这个问题。我在问Codepen是的好吧但为什么?你有枪指着你的头,强迫你使用密码笔吗?您可以使用stackblitz轻松地继续学习。。。