我正在尝试定义一个指令,如果用户没有某个声明,它会隐藏元素。
在我定义指令后,我在application.module声明中声明它。
问题是我无法使用嵌套在application.module中的模块的指令。如果我在应用程序模块的“下一个”组件内部使用该指令,它可以正常工作,但是当我使用嵌套模块内部的组件的指令时,编译器无法识别它并抛出错误,如果我再次声明该指令编译器会再次抛出,因为它正在其他地方声明。
答案 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
中的模块,其中包含declarations
和exports
中的指令
创建共享模块
@NgModule({
imports: [],
declarations: [MyDirective],
exports: [MyDirective],
}
export class SharedModule {}
并导入它,只要您想使用指令或管道:
@NgModule({
imports: [SharedModule],
declarations: [],
exports: [],
}
export class NestedModule {}
指令只能在一个模块的declarations
中。
如果要在各种模块中使用指令,则需要创建共享模块。