2 child modules access the same component in Angular error occured

Viewed 84

i have this psuedo code structure in my angular project.

wrapper.module
Wrapper.module.ts

@NgModule({
 declaration: [WrapperComponent.ts]
 imports: [
   WrapperRouting.module
 ]
})

wrapper-routing.module.ts
WrapperRouting.module

routes = [
 {
   path: '',
   component: wrapper.component.ts ,
   children: [
    { path: '', loadChildren: Component1.module.ts},
    { path: '2', loadChildren: Component2.module.ts},
   ]
 }
];

component1.module.ts

@NgModule({
   declaration: [Component1Component, ShowTableComponent]
   imports: [
     Component1Routing.module
   ]
 })

component1.component.ts

<show-table></show-table>

component2.module.ts

@NgModule({
   declaration: [Component2Component, ShowTableComponent]
   imports: [
     Component2Routing.module
   ]
 })

component2.component.ts

<show-table></show-table>

Im trying first to declar the ShowComponent in Component1.module.ts and Component2.module.ts however I got an error that ShowComponent is declared in two module.

Then, tried to put in the the parent module which is Wrapper.module.ts the error would be: ShowComponent is an Angular component, then verify that it is part of this module.

Can someone help me, much appreciated!

1 Answers

Can you please clarify how you are defining the parent-child relationship between all of these modules. Because there is no specific way to depict a parent-child relationship between modules in angular.

If you want to use the <show-table></show-table> in component1.module and component2.module, you have to add the wrapper.module in the imports array of both modules i.e. component1.module and component2.module and add the ShowComponent in the exports array of Wrapper.module.

After which your respective code will become as follows

Component1.module.ts

@NgModule({
   declarations: [
     Component1
   ],
   imports: [
     WrapperModule
   ]
})
export class Component1Module { }

Component2.module.ts

@NgModule({
   declarations: [
     Component2
   ],
   imports: [
     WrapperModule
   ]
})
export class Component2Module { }

wrapper.module.ts

@NgModule({
   declarations: [
     ShowComponent
   ],
   exports: [
     ShowComponent
   ]
})
export class WrapperModule { }

P.S. This method is used when you have to use a component from a different module in the HTML of a component. If you are using <router-outlet></router-outlet> you don't have to worry about importing the modules to use a component. You can just specify the name of the component in the routes array.

Do let me know if my answer helped you!

Related