@Component({
selector: 'my-component',
template: `<ng-content></ng-content>`,
providers: [
{ provide: SourceComponent, useExisting: forwardRef(() => TargetComponent) }
]
})
export class TargetComponent extends SourceComponent implements OnInit {
}
This component uses providers property in decorator. But I could not understand tha aim of the forwardRef() in here. In documentation says Allows to refer to references which are not yet defined. But if a reference is not definet it should throw exception.
So from the documentation for forwardRef() it says.
Allows to refer to references which are not yet defined.
It does basically what it says. It allows you to refer to a run-time reference before it has been defined.
Take the following example.
const x = Example;
// throws "Uncaught ReferenceError: Cannot access 'Example' before initialization"
const Example = "Hello";
In the above the variable Example is used before it is defined, and this triggers a run-time error.
We can fix this by using a function, because JavaScript parses scope at execution time.
const x = () => Example;
const Example = "Hello";
console.log(x()); // prints "Hello"
The above prints "Hello" because JavaScript evaluates the function when it is executed and the variable Example exists in the stack frame that declared the function.
Now look at your example and see that TargetComponent is being referenced before it is declared, but we avoid an error by using a function.
@Component({
// ....
providers: [
{ provide: SourceComponent, useExisting: forwardRef(() => TargetComponent) }
// ^^ not defined yet
]
})
export class TargetComponent extends SourceComponent implements OnInit {
// ^^ declared here lower in source code
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With