While I was in the process of migrating our Angular project to use Angular Standalone Components I bumped against an issue that I wasn't expecting. The problem was a circular dependency between two components that recursively rendered each other.
In our case, this is a list component that renders a list item component, and the list item component renders the same list component again. For each component to render the other component it needs to include the other component within its
imports array. This creates a circular dependency, which results in the following error:
With the previous version that used Angular modules, this did not cause any issues because both components were imported within the same module.
The workaround I came up with is to dynamically render the component, while this works it isn't very clean and requires some extra code changes.
So I went on Twitter, and again, the helpful Angular community came to the rescue.
It also seems that I'm not the only one that ran into this issue... A day later when I encountered the issue, another developer also ran into the same issue and posted a question on StackOverflow.
The solution to this problem is to utilize the
forwardRef function from
Allows to refer to references which are not yet defined.
I was already familiar with the
forwardRef function, but I did not know that it can be used to import standalone components.
Let's take a look at what this looks like.
The parent component (
ListComponent), is just a normal component that imports the child component (
There's nothing special to see here.
The magic happens in the child component (
Rather than directly importing the parent component (
ListComponent) from the child component, the child component uses
forwardRef to import the parent component.
I appreciate it if you would support me if have you enjoyed this post and found it useful, thank you in advance.