Search code examples
angulartypescriptangular2-decorators

declarations meta data of an NgModule


Is it possible to at runtime query the declarations of a module class that is decorated with an @NgModule.

@NgModule({
    imports: [
    ...
    ],
    declarations: [
        Component1,
        Component2,
        Component3
    ]
})
export class MyModule { }

So, what I am trying to accomplish is roughly:

const declarations: Type[] = MyModule.declarations;

Solution

  • I'm not entirely sure, but I believe in AOT mode this answer will not work. Apart from that, this is a private/naughty access property and subject to change, but you can access the definition like this:

    const descriptor = Reflect.getOwnPropertyDescriptor(MyModule, '__annotations__');
    
    if (descriptor) {
      const decorator = descriptor.value && descriptor.value[0];
    
      if (decorator) {
        const { declarations } = decorator; 
      }
    }