我使用的是带有webpack的Angular 4模板 当我尝试使用一个组件(ConfirmComponent)时,我有这个错误:

没有为ConfirmComponent找到组件工厂。你加进去了吗 @NgModule.entryComponents吗?

该组件在app.module.server.ts中声明

@NgModule({
  bootstrap: [ AppComponent ],
  imports: [
    // ...
  ],
  entryComponents: [
    ConfirmComponent,
  ],
})
export class AppModule { }

还有app。module。browser。ts和app。module。shared。ts

我该怎么解决呢?


当前回答

此错误发生在您尝试动态加载组件时,并且:

要加载的组件不是路由模块 该组件在模块entryComponents中为no。

在routingModule

const routes: Routes = [{ path: 'confirm-component', component: ConfirmComponent,data: {}}]

或者在模块中

entryComponents: [
ConfirmComponent
} 

要修复此错误,您可以将路由器添加到组件或添加到模块的entryComponents中。

添加路由器到组件。这种方法的缺点是你的 组件将通过该url访问。 将其添加到entryComponents中。在这种情况下,您的组件将没有附加任何url,它将无法通过url访问。

其他回答

如果在应用程序中使用路由

确保在路由路径中添加新组件

例如:

    const appRoutes: Routes = [
  { path: '', component: LoginComponent },
  { path: 'home', component: HomeComponent },
  { path: 'fundList',      component: FundListComponent },
];

在这里澄清一下。如果你不直接在组件中使用ComponentFactoryResolver,并且你想将它抽象为服务,然后将其注入到组件中,你必须在该模块的providers下加载它,因为如果延迟加载它将不起作用。

将此添加到module.ts中,

declarations: [
  AppComponent,
  ConfirmComponent
]

如果ConfirmComponent在另一个模块中,你需要导出它,这样你就可以在外面使用它,添加:

exports: [ ConfirmComponent ]

更新Angular 9或Angular 8,显式启用Ivy

使用Ivy的入口组件不再是必需的,现在已弃用

——用于禁用了Ivy的Angular 9和8——

在动态加载组件的情况下,为了生成ComponentFactory,该组件还必须添加到模块的entryComponents:

declarations: [
  AppComponent,
  ConfirmComponent
],
entryComponents: [ConfirmComponent],

根据entryComponents的定义

指定定义此模块时应编译的组件列表。对于这里列出的每个组件,Angular都会创建一个ComponentFactory,并将其存储在ComponentFactoryResolver中。

我也有同样的问题。在这种情况下进口[…]]是至关重要的,因为如果你不导入NgbModalModule,它将无法工作。

错误描述说组件应该添加到entryComponents数组中,这是显而易见的,但请确保您已经在第一个位置添加了这个:

imports: [
    ...
    NgbModalModule,
    ...
  ],

我在使用动态组件的ag网格中遇到了同样的问题。我发现你需要在ag-grid模块中添加动态组件。withcomponents []

进口:[ StratoMaterialModule, BrowserModule, AppRoutingModule, HttpClientModule, BrowserAnimationsModule, NgbModule.forRoot (), FormsModule, ReactiveFormsModule, AppRoutingModule, AgGridModule.withComponents (ProjectUpdateButtonComponent) ],