What does forwardRef do in angular, and what is its usage?
here is an example:
import {Component, Injectable, forwardRef} from '@angular/core';
export class ClassCL { value; }
@Component({
selector: 'my-app',
template: '<h1>{{ text }}</h1>',
providers: [{provide: ClassCL, useClass: forwardRef(() => ForwardRefS)}]
})
export class AppComponent {
text;
constructor( myClass: ClassCL ) {
this.text = myClass.value;
}
}
Injectable()
export class ForwardRefS { value = 'forwardRef works!' }
From Angular's API docs on forwardRef
:
Allows to refer to references which are not yet defined.
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.
There is a good write up at Angular In Depth.
Here's an extract:
Why does forwardRef work?
Now the question may pop up in your head how the
forwardRef
works. It actually has to do with how closures in JavaScript work. When you capture a variable inside a closure function it captures the variable reference, not the variable value. Here is the small example to demonstrate that:let a; function enclose() { console.log(a); } enclose(); // undefined a = 5; enclose(); // 5
You can see that although the variable
a
was undefined at the moment theenclose
function was created, it captured the variable reference. So when later the variable was updated to the5
it logged the correct value.And
forwardRef
is just a function that captures a class reference into closure and class becomes defined before the function is executed. Angular compiler uses the function resolveForwardRef to unwrap the token or provider type during runtime.