4

On the Angular 2 Style Guide, there is a recommendation for a directory structure: https://angular.io/docs/ts/latest/guide/style-guide.html#04-06

I generally think it's a good recommendation, I'd intend on doing something very similar myself. However, I've run into an issue with it, and I'm curious if anyone has resolved it.

Notice the heroes module contains a shared directory with a heroes-button.component. Presumably, we'll want to use this component all over the app (hence, "shared").

Likewise, the villains module contains a shared directory with a villains-button.component.

If I want to use the villains-button.component in some place in the heroes module and the heroes-button.component in the villains module, then I'm going to end up with a circular reference.

In short: Angular doesn't allow me to import a ModuleA into ModuleB, AND ModuleB into ModuleA, but the style guide indicates otherwise.

Does anyone have any solutions for this scenario?

Daniel Patrick
  • 3,980
  • 6
  • 29
  • 49
  • 2
    The style guide is suggesting components shared among each module are in the shared directory and are not referenced outside of that. Components that are shared across modules are in the upper level Shared directory /app/shared – silentsod Oct 13 '16 at 20:36
  • Did you get the solutions? I have ran into same issue where Module A is loaded into Module B and Module B loaded into Module A. While compiling application I ran into error of 'ERROR in Maximum call stack size exceeded'. – Parikh Vaibhav May 11 '17 at 04:23
  • @ParikhVaibhav, I've just added how I resolved this for future askers below. Let me know if that helps. – Daniel Patrick May 11 '17 at 10:47
  • @daniel: Thank you for your answer. What I was wondering was how we can do this for module containing routes as well. please see below SO question.http://stackoverflow.com/q/43907450/853523 – Parikh Vaibhav May 12 '17 at 03:47

1 Answers1

2

My solution to this was to move those components that were forcing me to have a circular dependency (in this case the villains-button.component and the heroes-button.component) into the Shared module.

In the end the directory structure looks like this:

HeroesModule
    -HeroComponentA
    -HeroComponentB
VillainsModule
     -VillainComponentA
     -VillainComponentB
SharedModule
     -HeroButton
     -Villain Button    <-- these two are now available across the application

It may not feel right, because you think the "Hero" button belongs with other Hero stuff, but in retrospect as my application has grown, I'm quite glad that Angular bars circular dependencies between Modules. That is a very dangerous pattern to support as the app grows.

Daniel Patrick
  • 3,980
  • 6
  • 29
  • 49