When you inject a token on a Component, the injection system will use a recursive pattern to inject the token an stops either once it has successfully found the token or once it has reach top injector. In some case we would like to create some kind of encapsulation and set a different boundary that the top injector.
@Self()
and @Host()
were created in order to create that kind of encapsulation, this allows injection to stop at respectively the current component or the host component.
Thoses decorators are not flexible and they only address two specific use case. Take for example a DataTable implementation as follow :
<table optionalDir>
<row>
<cell></cell>
</row>
<table>
If we want to inject optionalDir
on some child with an encapsulation set at table
, we can do it for row
using @Optional() @Host() optionalDir: OptionalDirective
but we can't do it at the cell level.
@Until(token)
So that decorator would trigger the following behavior : for each injector :
- Try to inject the dependency, if we succeed we're done.
- If we fail, try to resolve the token given as argument to Until
- On succeed we stop the lookup and return undefined
- On fail, repeat on parent injector.
I used resolve the token and not inject the token because if the resource associated with the token doesn't exist best case would be to not create it but just check it's available.
In our precedent example we could inject OptionalDirective
into row
and cell
as follow :
@Optional() @Until(TableComponent) optionalDir: OptionalDirective
token
could also be a number that defines how many times we should recurse, meaning @Until(0)
== @Self()
and @Until(1)
== @Host()
.
In that case token
should be renamed of course.