Angular 2不能使用指令形成嵌套模块

Vil*_*ius 1 angular2-directives angular

我正在尝试定义一个指令,如果用户没有特定声明,它将隐藏元素。

在我定义指令后,我在 application.module 声明中声明它。

问题是我无法使用嵌套在 application.module 中的模块中的指令。如果我在应用程序模块“旁边”的组件中使用指令,它工作正常,但是当我使用来自嵌套模块内部的组件的指令时,编译器无法识别它并抛出错误,如果我再次声明指令编译器再次抛出,因为它是在别处声明的。

Sur*_*yan 5

Declarations不被嵌套模块继承。您需要为每个要使用它的Directive位置添加您的声明。NgModule您还可以为您的指令创建一个包装器模块,例如YourDirectiveModule,将您的指令添加Directive到 中declarations,然后从 中导出它们YourDirectiveModule。然后将您的导入YourDirectiveModule到每个NgModule您想要使用它的地方。

@NgModule({
   declarations: [YourDirective],
   exports: [YourDirective]
})
export class YourDirectiveModule { }
Run Code Online (Sandbox Code Playgroud)

并使用

@NgModule({
   imports: [ YourDirectiveModule ]
})
export class SomeModule
Run Code Online (Sandbox Code Playgroud)


Gün*_*uer 5

每个使用指令的模块,都需要有指令 indeclarations或有模块 in imports,有指令 indeclarationsexports

创建共享模块

@NgModule({
  imports: [],
  declarations: [MyDirective],
  exports: [MyDirective],
}
export class SharedModule {}
Run Code Online (Sandbox Code Playgroud)

并将它导入到任何你想使用指令或管道的地方:

@NgModule({
  imports: [SharedModule],
  declarations: [],
  exports: [],
}
export class NestedModule {}
Run Code Online (Sandbox Code Playgroud)

指令只能在declarations一个模块中。如果要在各种模块中使用指令,则需要创建共享模块。