问题描述
我有应该在子模块和父模块中使用的标头.它被导入并在父模块中使用,但是当尝试在子组件中导入和使用时,它显示错误.我的意思是如何为父模块和父模块使用公共标头子模块
I have header that should be used in both child and parent module.that was imported and used in parent module but when try to import and using in child component it showing error.I mean how to use common header for both parent and child module
未捕获(承诺):错误:
Type HeaderComponent 是2 个模块的声明:AppModule 和 ProviderModule!请考虑将 HeaderComponent 移动到更高的导入模块AppModule 和 ProviderModule.
Type HeaderComponent is part of the declarations of 2 modules: AppModule and ProviderModule! Please consider moving HeaderComponent to a higher module that imports AppModule and ProviderModule.
你也可以创建一个新的 NgModule 来导出和包含HeaderComponent 然后在 AppModule 中导入 NgModule 和提供者模块.
You can also create a new NgModule that exports and includes HeaderComponent then import that NgModule in AppModule and ProviderModule.
推荐答案
你应该用你想要使用的组件创建一个共享模块,导出这些组件,并在你的其他模块中导入共享模块(你的父模块和子模块)案例).
You should create a shared module with the components you want to use, export these components, and import the shared module in your other modules (parent and child for your case).
共享模块:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { SharedComponent1 } from "./SharedComponent1";
import { SharedComponent2 } from "./SharedComponent2";
@NgModule({
imports: [
CommonModule
],
declarations: [
SharedComponent1,
SharedComponent2
],
exports: [
SharedComponent1,
SharedComponent2
]
})
export class SharedModule {}
使用共享模块:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
...
import { SharedModule } from './SharedModule';
@NgModule({
imports: [
CommonModule,
...
SharedModule
],
declarations: [
...
],
providers: [
...
]
})
export class AppModule{}
这篇关于如何在angular2的子模块组件中使用父模块组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!