Workaround for Circular component blocked imports in Angular
Circular components in html templates
Published: 6/8/2024Circular components in html templates#
Scenario:
- I had a form component that calls ui component
- The ui component iterates through the given ui items
- One item type is an array input component, which iterates through its items calling the ui component
Issue:
- Circular dependencies
- ui component calls array component, and
- array component calls ui component
Error: ReferenceError: Cannot access 'UiComponent' before initialization
Resolution:
- Import the ui component using forwardRef instead of directly.
@Component({
selector: 'app-array',
templateUrl: './array.component.html',
styleUrls: ['./array.component.scss'],
standalone: true,
imports: [
// UiComponent,
forwardRef(() => UiComponent),
],
})
export class ArrayComponent {}
- The Angular
forwardRef()function creates an indirect reference that Angular can resolve later.