Access Meta-Annotation inside Class (TypeScript)

With the new angular version, you should use the native Reflect object. No IE11 support though:

const annotations = Reflect.getOwnPropertyDescriptor(MyModule, '__annotations__').value;

Read Jeff Fairley’s answer below on what to do with the data after that


You can see an annotation/decorator as a normal function call. To this function the ‘Class/Function’ object (not instance) gets send in the first parameter, and the parameters (metadata) in the second argument.

However it depends on the implementation of that function if something gets added for instance to the prototype of the class (bad practice/exposing property). The TypeScript compiler and Angular2 do things differently though.

They use the __decorate and __metadata functions, which are generated by the TypeScript compiler. The data gets added with the Object.defineProperty() function. The package responsible for this is Reflect. (which under the hood uses the Object.defineProperty() function in combination with a WeakMap).

The function Reflect.defineMetadata() is used to set the annotations, and to obtain them the obvious Reflect.getMetadata().

TLDR;

  • To get the annotations from a class/component in angular2, you have
    to use:

    Reflect.getMetadata('annotations', ComponentClass); //@Component({}), @Pipe({}), ...
    
  • To get the annotations from the constructor paramaters in angular2, you have to use:

    Reflect.getMetadata('parameters', ComponentClass); //@Inject()
    
  • To get the annotations from a property in a class in angular2, you
    have to use:

    Reflect.getMetadata('propMetadata', ComponentClass); //@HostBinding(), @Input(), ...
    

Leave a Comment