Fixing Circular Imports in Angular using Injection Tokens

May 10, 2020 13:31 · 177 words · 1 minute read angular typescript dependency-injection

Circular Imports in angular

This is not something directly related to Angular but programming in general. Most common use cases involve parent directive/component querying for children via @ContentChildren() and later on those same child components injecting aforementioned parent.

Let us set up our suspects

There are three things we will need:

  1. Injection token and interface
  2. Parent directive that will be used as element here (not attribute selector): <parent-dir>... child components here... </parent-dir> . The directive will gather children via @ContentChildren and update their props as proof we can use them.
  3. Children components that will inject (via constructor) aforementioned parent directive and display its prop in their template. Take note at this point we would have a circular import error if we were injecting the directive directly.

First we set up interface to represent our parent directive and corresponding injection token:

Now we declare parent directive that will provide itself under the declared token:

The child components are now ready to inject parent directive

And finally putting it to test:

Stackblitz demo for the example above:

Circular imports in Angular on Stackblitz