← Back to Angular, page 7

angular-0125 · Medium mid

What is forwardRef in Angular, when do you need it, and how do you solve circular dependencies properly?

forwardRef lets you refer to a class that is declared later in the file, because classes are not available before their declaration runs. It is needed in decorator metadata such as NG_VALUE_ACCESSOR providers. A real circular dependency between services, where A needs B and B needs A, should be removed by redesigning, not hidden.

Full answer

In JavaScript, a class declaration is not usable before the line where it is declared (it is in the "temporal dead zone"). Decorators are evaluated when the class is defined, so this fails:

@Component({ providers: [{ provide: NG_VALUE_ACCESSOR, useExisting: MyInput, multi: true }] }) export class MyInput { }

When the decorator runs, MyInput is not yet initialised, so the reference throws or is undefined. forwardRef(() => MyInput) delays the lookup: it stores an arrow function and Angular calls it later, when the class exists. This is why every custom form control needs useExisting: forwardRef(() => MyInput).

You also meet it with imports: [forwardRef(() => OtherComponent)] when two standalone components reference each other (a recursive tree of components, where a node component contains itself, does not need it because a component can refer to itself in its own template).

A different problem is a true circular dependency of services: AuthService injects UserService, and UserService injects AuthService. Angular can not create one before the other and throws NG0200: Circular dependency in DI detected. forwardRef does not fix this. Options, from best to worst:

  1. Redesign: extract the shared part into a third service (SessionStore) that both depend on. This is the real fix and usually shows a missing concept.
  2. Replace one direction with events or a stream: the second service emits, the first subscribes.
  3. Inject lazily: inject(Injector) and call injector.get(UserService) when needed (after both exist). This works but hides the dependency, so use it sparingly.

Also watch for circular file imports (A imports B and B imports A at the top). Bundlers may produce undefined at start-up. Tools such as madge or the lint rule import/no-cycle detect them.

typescript
import { Component, Injectable, forwardRef, inject } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';

// 1. forwardRef is needed because the class is referenced inside its own decorator.
@Component({
  selector: 'app-rating',
  providers: [{ provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => RatingComponent), multi: true }],
  template: `Rating`,
})
export class RatingComponent implements ControlValueAccessor {
  writeValue(): void {}
  registerOnChange(): void {}
  registerOnTouched(): void {}
}

// 2. A real circular dependency. forwardRef does not help here.
@Injectable({ providedIn: 'root' })
export class AuthService {
  readonly users = inject(UserService);
}

@Injectable({ providedIn: 'root' })
export class UserService {
  readonly auth = inject(AuthService);
}

// Fix: both depend on a third service that owns the shared state.
@Injectable({ providedIn: 'root' })
export class SessionStore {
  userName: string | null = null;
}

@Injectable({ providedIn: 'root' })
export class FixedAuthService {
  readonly session = inject(SessionStore);
}

@Injectable({ providedIn: 'root' })
export class FixedUserService {
  readonly session = inject(SessionStore);
}

Angular 20.3, type-checked. A Karma test creates the injector with two services that need each other and confirms that the error is NG0200. The input component with forwardRef is the fixed form shown below.

Key points

  • `forwardRef` delays a class reference until the class is initialised, for decorator metadata.
  • Custom form controls use it in `NG_VALUE_ACCESSOR` providers.
  • It does not fix circular service dependencies (NG0200). Redesign them.
  • Detect circular imports with lint or tooling.

Common mistakes

  • Using `forwardRef` to hide a real circular service dependency.
  • Writing `useExisting: MyInput` without `forwardRef` in the class's own decorator.
  • Ignoring circular file imports until a mysterious `undefined` appears.

Follow-ups

  • Why are decorators evaluated before the class is ready?
  • How would you break the Auth and User service cycle?
  • What does `NG0200` tell you?

Tips

  • Explain the temporal dead zone in one sentence.
  • Separate "reference order" from "circular dependency".
  • Offer the third service solution first.

Evaluation rubric

  • Explains why forwardRef exists.
  • Distinguishes it from circular dependency errors.
  • Gives sound design solutions.