Angular 2 不能使用嵌套模块的指令
Angular 2 Cannot use directive form a nested module
我正在尝试定义一个指令,如果用户没有特定声明,该指令将隐藏元素。
定义指令后,我在 application.module 声明中声明它。
问题是我无法使用嵌套在 application.module 中的模块中的指令。如果我在应用程序模块 'next' 的组件内部使用指令,它工作正常,但是当我使用嵌套模块内部组件的指令时,编译器无法识别它并抛出错误,并且如果我再次声明该指令,编译器将再次抛出,因为它正在其他地方声明。
Declarations
不会被嵌套模块继承。您需要将 Directive
添加到每个要使用它的 NgModule
的声明中。你也可以为你的指令提供一个包装器模块,比如 YourDirectiveModule
,将你的 Directive
添加到 declarations
中,然后从 YourDirectiveModule
中导出它们。然后将您的 YourDirectiveModule
导入到您要使用它的每个 NgModule
中。
@NgModule({
declarations: [YourDirective],
exports: [YourDirective]
})
export class YourDirectiveModule { }
并使用
@NgModule({
imports: [ YourDirectiveModule ]
})
export class SomeModule
每个使用指令的模块都需要在 declarations
中包含指令,或者在 imports
中包含指令,在 declarations
和 exports
中包含指令
创建共享模块
@NgModule({
imports: [],
declarations: [MyDirective],
exports: [MyDirective],
}
export class SharedModule {}
并在任何你想使用它的指令或管道的地方导入它:
@NgModule({
imports: [SharedModule],
declarations: [],
exports: [],
}
export class NestedModule {}
一个指令只能在一个模块的 declarations
中。
如果要在各个模块中使用指令,则需要创建一个共享模块。
我正在尝试定义一个指令,如果用户没有特定声明,该指令将隐藏元素。
定义指令后,我在 application.module 声明中声明它。
问题是我无法使用嵌套在 application.module 中的模块中的指令。如果我在应用程序模块 'next' 的组件内部使用指令,它工作正常,但是当我使用嵌套模块内部组件的指令时,编译器无法识别它并抛出错误,并且如果我再次声明该指令,编译器将再次抛出,因为它正在其他地方声明。
Declarations
不会被嵌套模块继承。您需要将 Directive
添加到每个要使用它的 NgModule
的声明中。你也可以为你的指令提供一个包装器模块,比如 YourDirectiveModule
,将你的 Directive
添加到 declarations
中,然后从 YourDirectiveModule
中导出它们。然后将您的 YourDirectiveModule
导入到您要使用它的每个 NgModule
中。
@NgModule({
declarations: [YourDirective],
exports: [YourDirective]
})
export class YourDirectiveModule { }
并使用
@NgModule({
imports: [ YourDirectiveModule ]
})
export class SomeModule
每个使用指令的模块都需要在 declarations
中包含指令,或者在 imports
中包含指令,在 declarations
和 exports
中包含指令
创建共享模块
@NgModule({
imports: [],
declarations: [MyDirective],
exports: [MyDirective],
}
export class SharedModule {}
并在任何你想使用它的指令或管道的地方导入它:
@NgModule({
imports: [SharedModule],
declarations: [],
exports: [],
}
export class NestedModule {}
一个指令只能在一个模块的 declarations
中。
如果要在各个模块中使用指令,则需要创建一个共享模块。