how to use parent module component in child module component in angular2

和自甴很熟 提交于 2020-01-31 06:47:47

问题


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

Uncaught (in promise): Error:

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.

You can also create a new NgModule that exports and includes HeaderComponent then import that NgModule in AppModule and ProviderModule.


回答1:


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).

Shared module:

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 {}

Using Shared module:

import { NgModule }       from '@angular/core';
import { CommonModule }   from '@angular/common';
...
import { SharedModule } from './SharedModule';

@NgModule({
imports: [
    CommonModule,
    ...
    SharedModule
],
declarations: [
    ...
],
providers: [
    ...
]
})
export class AppModule{}



回答2:


It would have been great , if you can share the code and the specified the error you are getting.

As per my understanding , you basically want to pass some data from parent component to its child component .

For this , you need to use @Input to pass parent params to child.

Component Interaction between parent and child

Let me know , if it helps or not



来源:https://stackoverflow.com/questions/44471095/how-to-use-parent-module-component-in-child-module-component-in-angular2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!