0

I have 2 parent component and 1 child component. And my project structure is below:

app
   -> app.module.ts
   -> app.component.ts
   -> app.routing.module.ts
parentComponent1
   -> parent1.module.ts
   -> parent1.component.ts
parentComponent2
   -> parent2.module.ts
   -> parent2.component.ts
childComponent
   -> child.module.ts
   -> child.component.ts

Now my problem is when i am using child componet's selector in parentComponent1 and parentComponent2 as :

<child-component [name]="parent1"></child-component>

And importing child module in both parent component as :

parent1.module.ts--

 @NgModule({
          imports:[ChildModule],
           declarations:[ChildComponent]
})
----
---- 
and so on....

And same in parentComponent2's Moudle as :

parent2.module.ts--

 @NgModule({
              imports:[ChildModule],
               declarations:[ChildComponent]
    })
    ----
    ---- 
    and so on....

Now when i starts my project, my default routes go to parentComponent1 and there is no error in console and it works fine, but when i go to parentComponent2, then the error comes in console as :

Unhandled Promise rejection: Type ChildComponent part of the declarations of 2 modules: Parent1Module and Parent2Module! Please consider moving ChildComponent to a higher module that imports Parent1Module and Parent2Module . You can also create a new NgModule that exports and includes ChildComponent then import that NgModule in Parent1Module and Parent2Module

.

Please help me out what wrong i am doing here.

1
  • You are importing Child in Parent ? Seems something wrong in logical structure.
    – Amit
    Mar 24, 2017 at 7:28

1 Answer 1

8

Use this solution

You should not declarations a component in more than one NgModule, you could export in one NgModule, then import this NgModule in other NgModule.

child.module.ts

@NgModule({
  imports:[...],
  declarations:[ChildComponent],
  exports:[ChildComponent]
})

parent1.module.ts

@NgModule({
  imports:[ChildModule],
  declarations:[...]
})

parent2.module.ts

@NgModule({
  imports:[ChildModule],
  declarations:[...]
})
2
  • Thanks Mr Tiep Phan for the clean and accurate answer :) Now its working fine. Mar 24, 2017 at 7:31
  • glad to help you!
    – Tiep Phan
    Mar 24, 2017 at 7:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.