Dynamically access the declarations array of my Angular module

44 Views Asked by At

I recently upgraded a project from Angular 9 to 17. Everything finally went together (although after quite a struggle), but I wanted to go further and reorganize the whole thing, so I created a new project from scratch with Angular 17, and stumbled upon a problem I don’t understand, and can’t resolve.

My project has a module and some components which can be different from one build to another. In other words, I boot on a unique module, but also load a module which exists in different version (I of course load only one of the different versions each time I build my project).

To be able to dynamically instantiate the components declared in the dynamic module from their name, I loop on the declarations array with MyModule.prototype.constructor['ɵmod'].declarations of my module and map each component to its name. I then use this map in a dynamic-component-loader to retrieve the component from its name and instantiate it.

import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';
import { TestComponent } from '../test/test.component';

@NgModule({
  declarations: [
    TestComponent
  ],
  imports: [
    CommonModule
  ]
})
export class TestModule {
  constructor() {
    let test = {};
    TestModule.prototype.constructor['ɵmod'].declarations.forEach(component => {
      test[component.name] = component;
    });
  }
}

Everything works fine in my old project, even now that it’s upgraded to Angular 17.

However, in the project I’ve created directly under Angular 17, the declarations array remains empty. In fact, the whole TestModule object is well defined, but completely empty of all references.

My questions are:

  1. Why does this happen?
  2. Can I force Angular to fill the object?
  3. If not, where else can I access a filled declarations array?

Thank you all.

0

There are 0 best solutions below