2

I recently started using ViewChildren and ContentChildren in Angular 2, but had now been wondering if these could be used in ES6 without TypeScript annotations as well.

The TypeScript syntax, as per the docs, is as follows:

@ViewChild(ItemDirective) viewChild: ItemDirective;

Alternatively, as per here:

// myVideo == #my-video
@ViewChild('myVideo') myVideo: any;

Now, the corresponding source has Metadata classes for ViewChild and co., which I recall could be used to add some of the other annotations in plain JS. So I'm thinking it should be doable, but I'm not really sure how in this case. Would anyone be able to shed some light on this?

Community
  • 1
  • 1
Kiara Grouwstra
  • 5,723
  • 4
  • 21
  • 36

1 Answers1

2

I think that such decorators should work with ES6 / ES7 (you need to include ES7 decorators in addition to ES6 itself). The latter does have are class and property decorators so you should be able to transpile the ViewChild decorator.

It's not the same for parameter decorators that aren't supported...

See this answer and its comments:

This link could be also useful:

Community
  • 1
  • 1
Thierry Templier
  • 198,364
  • 44
  • 396
  • 360
  • Thanks, this is hella interesting; the babel plugins/transformers mentioned there just allowed me to convert all of my TS to ES6/7... except for one line. Ironically that's exactly my one `@ViewChild` line. :( That does actually seem like it could be a bug though, so perhaps I should also try and file an issue at [`babel-plugin-angular2-annotations`](https://github.com/shuhei/babel-plugin-angular2-annotations)... If that lib does still get this done, then consider this solved. – Kiara Grouwstra Feb 07 '16 at 17:17
  • Couldn't edit my comment anymore, but now filed it [on there](https://github.com/shuhei/babel-plugin-angular2-annotations/issues/18). – Kiara Grouwstra Feb 07 '16 at 17:37
  • I noticed the decorator wasn't able to take variables, and eventually found that the working TypeScript transpilation just used `Reflect.decorate`. I ended up just calling that now; since it allows variables it's the only solution so far that fulfills my requirements (though a tad more verbose), while being cool with JS too. Thanks. – Kiara Grouwstra Feb 10 '16 at 12:15