Angular动态加载组件报错:No component factory found for XXXXComponent. Did you add it to @NgModule.entryComponents?

时间:2021-01-11 17:48:06

Angular在加载动态组件需要在@NgModule的entryComponents声明组件。否则会报类似以下的错误:

DialogComponent.html:51 ERROR Error: No component factory found for DialogComponent. Did you add it to @NgModule.entryComponents?
  at noComponentFactoryError (core.es5.js:3202)
  at CodegenComponentFactoryResolver.webpackJsonp.../../../core/@angular/core.es5.js.CodegenComponentFactoryResolver.resolveComponentFactory (core.es5.js:3267)
  at PortalHostDirective.webpackJsonp.../../../cdk/esm5/portal.es5.js.PortalHostDirective.attachComponentPortal (portal.es5.js:500)
  at MatDialogContainer.webpackJsonp.../../../material/esm5/dialog.es5.js.MatDialogContainer.attachComponentPortal (dialog.es5.js:136)
  at MatDialog.webpackJsonp.../../../material/esm5/dialog.es5.js.MatDialog._attachDialogContent (dialog.es5.js:635)
  at MatDialog.webpackJsonp.../../../material/esm5/dialog.es5.js.MatDialog.open (dialog.es5.js:538)
  at MenuComponent.webpackJsonp.../../../../../src/app/menu/menu.component.ts.MenuComponent.openDialog (menu.component.ts:46)
  at Object.eval [as handleEvent] (MenuComponent.html:51)
  at handleEvent (core.es5.js:11998)
  at callWithDebugContext (core.es5.js:13467)

在@NgModule的entryComponents声明组件:

@NgModule({
  imports: [
    CommonModule,
    AppRoutingModule
  ],
  entryComponents: [DialogComponent],
  declarations: [DialogComponent],
  providers: [AppService]
})
export class AppModule { }

在例子里DialogComponent是一个弹出框组件,动态加载。