How to retrieve a component's metadata in Angular

前端 未结 1 1893
礼貌的吻别
礼貌的吻别 2020-12-16 04:07

An Angular component has decorators:

@Component({ ... })
export class MyAngularComponent {
  @Input() myInputParam: MyType;
  @Input() myOtherInputParam: MyO         


        
相关标签:
1条回答
  • 2020-12-16 05:07

    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... How does Angular stores the decorators?

    In fact, Angular plans to remove dependency on the Reflect object even in runtime. For that reason, in the newest v5 the Reflect.defineMetadata has been replaced with Object.defineProperty in the makeDecorator that is responsible for attaching the metadata to the class. Here is the relevant code:

    export const ANNOTATIONS = '__annotations__';
    export function makeDecorator(
        ...
        const TypeDecorator: TypeDecorator = <TypeDecorator>function TypeDecorator(cls: Type<any>) {
          // Use of Object.defineProperty is important since it creates non-enumerable property which
          // prevents the property is copied during subclassing.
          const annotations = cls.hasOwnProperty(ANNOTATIONS) ?
              (cls as any)[ANNOTATIONS] :
              Object.defineProperty(cls, ANNOTATIONS, {value: []})[ANNOTATIONS]; <-----
          annotations.push(annotationInstance);
          return cls;
        };
    

    It means that in the v5 you can access decorators on the component class like this:

    export class AppComponent {
        constructor() {
            console.log((<any>AppComponent).__annotations__);
        }
    

    Is there a reliable, future-proof way to read them? I don't think there's anything future-proof with Angular.

    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.

    0 讨论(0)
提交回复
热议问题