【问题标题】:Angular 2 - Directives declared yet still have errorsAngular 2 - 声明但仍有错误的指令
【发布时间】:2016-09-01 10:05:32
【问题描述】:

RootModule:

@NgModule({
    imports: [
        ModuleA
    ],
    declarations: [
        ScrollToWhen
    ],
    bootstrap: [BootComponent],
})
class RootModule {}

在模块 A 内的一个组件模板中,我使用 ScrollToWhen,但出现错误:Can't bind to 'scrollToWhen' since it isn't a known property of 'div'

为什么?

Error: Unexpected directive 'HbClass' imported by the module 'Module'

【问题讨论】:

  • 我们需要更多信息,你如何使用指令,指令的代码是什么样的,...
  • 最好是通过代码而不是截图。 HbClassDefaultAssetPhoton 是模块吗?你有它们在declarationsRootModuleimportsModuleimports 用于模块,declarations 用于指令、组件和管道。
  • 所以我应该创建一个MyAppCommonModule 并在其中声明所有常用的指令和管道,然后在需要时导入到模块?
  • 就是这样。

标签: angular angular2-directives


【解决方案1】:

要么将ScrollToWhen 添加到ModuleA 的声明中,要么将其移动到一个模块中,然后您可以将其添加到ModuleAimports: [...] 中以使其可用。

一个组件/指令只能在declarations: [...]一个模块中列出。然后在任何你想使用这个组件/指令的地方导入这个模块。

对于用于声明指令和管道的模块,您需要在exports中设置它们,如:

@NgModule({
    declarations: [
        myDirectives
    ],
    exports: [
        myDirectives
    ]
})

【讨论】:

  • 感谢您指出我错过添加的配置。然而,在模块 A 中添加 import 配置后,我得到:Error: Unexpected directive 'MyDirective' imported by the module 'Module'
  • 你在哪里添加了什么import?您能否更新您的问题以显示您现在拥有的内容?
  • 我嵌入了截图
  • imports: [] 不能包含指令,只能包含模块。正如错误消息所说,它不是一个模块。指令应该进入恰好一个模块的declarations: [...],然后将此模块添加到您要使用它的模块的imports: []
猜你喜欢
  • 1970-01-01
  • 2017-02-02
  • 2017-06-11
  • 1970-01-01
  • 2017-10-19
  • 1970-01-01
  • 2015-07-08
  • 2017-04-05
  • 2017-09-21
相关资源
最近更新 更多