Cookies concent notice

This site uses cookies from Google to deliver its services and to analyze traffic.
Learn more
Skip to main content
This site is no longer updated.Head to Angular.devHome
/

This is the archived documentation for Angular v17. Please visit angular.dev to see this page for the current version of Angular.

forwardRef

Allows to refer to references which are not yet defined.

See more...

      
      forwardRef(forwardRefFn: ForwardRefFn): Type<any>
    
Parameters
forwardRefFn ForwardRefFn
Returns

Type<any>

Description

For instance, forwardRef is used when the token which we need to refer to for the purposes of DI is declared, but not yet defined. It is also used when the token which we use when creating a query is not yet defined.

forwardRef is also used to break circularities in standalone components imports.

Further information is available in the Usage Notes...

Usage notes

Circular dependency example

      
      @Injectable()
class Door {
  lock: Lock;

  // Door attempts to inject Lock, despite it not being defined yet.
  // forwardRef makes this possible.
  constructor(@Inject(forwardRef(() => Lock)) lock: Lock) {
    this.lock = lock;
  }
}

// Only at this point Lock is defined.
class Lock {}

const injector = Injector.create({
  providers: [
    {provide: Lock, deps: []},
    {provide: Door, deps: [Lock]},
  ],
});

expect(injector.get(Door) instanceof Door).toBe(true);
expect(injector.get(Door).lock instanceof Lock).toBe(true);
    

Circular standalone reference import example

      
      @Component({
  standalone: true,
  imports: [ChildComponent],
  selector: 'app-parent',
  template: `<app-child [hideParent]="hideParent"></app-child>`,
})
export class ParentComponent {
  @Input() hideParent: boolean;
}


@Component({
  standalone: true,
  imports: [CommonModule, forwardRef(() => ParentComponent)],
  selector: 'app-child',
  template: `<app-parent *ngIf="!hideParent"></app-parent>`,
})
export class ChildComponent {
  @Input() hideParent: boolean;
}