The "Maximum call stack size exceeded" happens because you try to import module1 in module2 and vice-versa. Angular will try to import modules in an infinite loop resulting with this error, as I could reproduce in this
StackBlitz
Given that you cannot declare a component in 2 modules, there are 2 usual solutions :
- Create a shared module and put all your reusable components in it (suitable for small projects)
- Create a mono-component module for each reusable component (better as you will only import module for components you will actually use, resulting in lighter modules.
EDIT : now, in 2024, standalone components might be a better solution than mono-component modules
For example, with the mono-component module :
Define the component :
@Component({
selector: 'app-shared-component',
template: '<div>Shared Component</div>',
})
export class MySharedComponent {}
Declare it in a module and export it :
@NgModule({
imports: [],
declarations: [MySharedComponent],
exports: [MySharedComponent],
})
export class MySharedComponentModule {}
Then you can import it in 2 different modules :
@Component({
selector: 'app-component-1',
template: '<h1>Component 1</h1><app-shared-component></app-shared-component>',
})
export class MyComponent1 {}
@NgModule({
imports: [MySharedComponentModule],
declarations: [MyComponent1],
exports: [MyComponent1],
})
export class Module1 {}
@Component({
selector: 'app-component-2',
template: '<h1>Component 2</h1><app-shared-component></app-shared-component>',
})
export class MyComponent2 {}
@NgModule({
imports: [MySharedComponentModule],
declarations: [MyComponent2],
exports: [MyComponent2],
})
export class Module2 {}
Then import those 2 modules and use them :
@NgModule({
imports: [BrowserModule, FormsModule, Module1, Module2],
declarations: [AppComponent],
bootstrap: [AppComponent],
})
export class AppModule {}
Working StackBlitz here