Help Angular by taking a 1 minute survey!Go to surveyHome

forwardRef

Allows to refer to references which are not yet defined.

See more...

forwardRef(forwardRefFn: ForwardRefFn): Type<any>
      
      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.

Usage notes

Example

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 = ReflectiveInjector.resolveAndCreate([Door, Lock]); const door = injector.get(Door); expect(door instanceof Door).toBeTruthy(); expect(door.lock instanceof Lock).toBeTruthy();
      
      
  1. class Door {
  2. lock: Lock;
  3.  
  4. // Door attempts to inject Lock, despite it not being defined yet.
  5. // forwardRef makes this possible.
  6. constructor(@Inject(forwardRef(() => Lock)) lock: Lock) { this.lock = lock; }
  7. }
  8.  
  9. // Only at this point Lock is defined.
  10. class Lock {}
  11.  
  12. const injector = ReflectiveInjector.resolveAndCreate([Door, Lock]);
  13. const door = injector.get(Door);
  14. expect(door instanceof Door).toBeTruthy();
  15. expect(door.lock instanceof Lock).toBeTruthy();