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

时间:2017-08-20 15:07:27

标签: angular angular2-directives

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

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

问题是我无法使用嵌套在application.module中的模块的指令。如果我在应用程序模块的“下一个”组件内部使用该指令,它可以正常工作,但是当我使用嵌套模块内部的组件的指令时,编译器无法识别它并抛出错误,如果我再次声明该指令编译器会再次抛出,因为它正在其他地方声明。

2 个答案:

答案 0 :(得分:4)

Declarations不会被嵌套模块继承。您需要将Directive添加到要使用它的每个NgModule的声明中。您也可以为YourDirectiveModule指令设置包装模块,将Directive添加到declarations,然后从YourDirectiveModule导出。{1}}。然后将YourDirectiveModule导入到您要使用它的每个NgModule

@NgModule({
   declarations: [YourDirective],
   exports: [YourDirective]
})
export class YourDirectiveModule { }

并使用

@NgModule({
   imports: [ YourDirectiveModule ]
})
export class SomeModule

答案 1 :(得分:4)

每个使用指令的模块都需要在declarations中使用该指令,或者使用imports中的模块,其中包含declarationsexports中的指令

创建共享模块

@NgModule({
  imports: [],
  declarations: [MyDirective],
  exports: [MyDirective],
}
export class SharedModule {}

并导入它,只要您想使用指令或管道:

@NgModule({
  imports: [SharedModule],
  declarations: [],
  exports: [],
}
export class NestedModule {}

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