Skip to content

Instantly share code, notes, and snippets.

@ghetolay
Last active April 16, 2017 21:47
Show Gist options
  • Save ghetolay/1b9a87725529d3466ea0bb650d827e93 to your computer and use it in GitHub Desktop.
Save ghetolay/1b9a87725529d3466ea0bb650d827e93 to your computer and use it in GitHub Desktop.
@until() injection decorator proposal for Angular

Problem / Need

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.

Current solution

@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.

Problem

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() proposal

@Until(token)

So that decorator would trigger the following behavior : for each injector :

  1. Try to inject the dependency, if we succeed we're done.
  2. 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

Possible extension

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment