An Angular component has decorators:
@Component({ ... })
export class MyAngularComponent {
@Input() myInputParam: MyType;
@Input() myOtherInputParam: MyOtherType;
@Output() myOutputParam: MyOtherOutputType;
}
I've got an Angular library where a lot of code repetitions could be avoided (and bundle size reduced) if I could programmatically retrieve Angular's @Input()
decorators inside a given component class (that belongs to the library, though).
But I have doubts on the portability of such an implementation. I've read somewhere that the Reflect polyfill (needed to read decorators at runtime) isn't needed if the Angular app has been built with AoT enabled (and given that only Angular decorators are used). So I presume I can't just use Reflect.*
. How does Angular stores the decorators? Is there a reliable, future-proof way to read them?
Minification shouldn't be a problem since that would be used to read decorators of library's components only, so I have control on this.
So, if that's doable in a portable way (or not, I'm still interested otherwise), how can I read those decorators?
In fact, Angular plans to remove dependency on the
Reflect
object even in runtime. For that reason, in the newest v5 theReflect.defineMetadata
has been replaced withObject.defineProperty
in themakeDecorator
that is responsible for attaching the metadata to the class. Here is the relevant code:It means that in the v5 you can access decorators on the component class like this:
When compiling an application using AOT Angular uses static code analysis and heavily relies on the AST produced by the TS compiler. If you're interested in accessing decorators in the build time I guess that is the way to go and I would call it the most future-proof solution.