Skip to content

Add some way to mimick the various dependency injections in ng2 (@Parent, @Query, etc) #22

Description

@timkindberg

See: https://angular.io/docs/js/latest/api/annotations/DirectiveAnnotation-class.html. There are various dependencies you can inject into the controller class constructor.

  1. directive:DirectiveType: a directive on the current element only
  2. @Ancestor() directive:DirectiveType: any directive that matches the type between the current element and the Shadow DOM root. Current element is not included in the resolution, therefore even if it could resolve it, it will be ignored.
  3. @Parent() directive:DirectiveType: any directive that matches the type on a direct parent element only.
  4. @Query(DirectiveType) query:QueryList<DirectiveType>: A live collection of direct child directives.
  5. @QueryDescendants(DirectiveType) query:QueryList<DirectiveType>: A live collection of any child directives.

In angular 1:

  • 1 is similar to using a require: 'dependency'. So no implementation needed.
  • 2 & 3 are similar to `require: '^depencency'. So no implementation needed.
  • 4 & 5 don't have a direct correlation in ng1. We'd have to write a custom method that queried child directives and watched for changes so it was live. Also the found children would have to properly reference each child's controller class instance.

Thoughts on 4 & 5: Perhaps an api like this would be possible, where we auto-generate a $Query method on every component class that would help with this:

@Component({ selector: 'child-a' })
class ChildA {
  foo() { console.log('foo') }
}

@Component()
@View({
  inline: `
    <child-a/>
    <child-a/>
  `
})
class MyComponent {
  constructor() {
    let childrenA = this.$Query(ChildA);
    console.log(childrenA.length); // outputs 2
    console.log(childrenA[0].foo()); // outputs 'foo'
  }
}

Activity

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions