EntryComponents in Module for LazyLoading

Polaris picture Polaris · Feb 21, 2018 · Viewed 8.5k times · Source

I want to load a modal from a component. In Angular Material documentation is write to add the modal component in entryComponents :

This :

@NgModule({
  imports: [
    CommonModule,
    AidesRoutingModule
  ],
  declarations: [TypesAidesComponent, TypesAidesAjouterComponent],
  entryComponents : [TypesAidesAjouterComponent]
})
export class AidesModule {

}

In TypesAidesComponent I want open dialog with TypesAidesAjouterComponent :

let dialog = this.dialog.open(TypesAidesAjouterComponent);
    dialog.afterClosed().subscribe(res => {
      if(res){
        this.collection.addItem(res);
      }
    });

I'm in a component lazyloading :

{
        path: 'types-aides',
        loadChildren: 'app/modules/aides/aides.module#AidesModule'
    },

But I have this error :

Error: No component factory found for TypesAidesAjouterComponent. Did you add it to @NgModule.entryComponents?

I have found a solution, it is to move remove the LazyLoading but my application is large and is not a possibility.

Do you have any suggestions ?

Answer

joshrathke picture joshrathke · Feb 21, 2018

This is a common complaint with Angular at the moment. In certain instances, extracting a small component out of a lazy loaded module is not possible because of how dependency injection works. Components have to be brought into the application through their respective Module, which means if the module hasn't been loaded, you can't use any of the Components it declares.

I had to come to terms with the fact that there really are very few instances where this need arises in a well structured application, and that bumping up against it should be a sign that I needed to re-evaluate the structure of the application.

The best way to get around this issue is to extract the component and either create a separate module for it, or add it to a shared module that is imported into the module you are rendering it within.