我使用的是带有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

我该怎么解决呢?


当前回答

我在Angular7中创建动态组件时也遇到了同样的问题。有两个组件(TreatListComponent, MyTreatComponent)需要动态加载。我只是在我的app.module.ts文件中添加了entryComponents数组。

    entryComponents: [
    TreatListComponent,
    MyTreatComponent
  ],

其他回答

入口组件是至关重要的。以上答案是正确的。

但是…

如果您正在提供打开模式(一种常见模式)的服务 你的模块定义了对话框组件没有加载到AppModule中,你需要将providedIn: 'root'更改为providedIn: MyModule。作为一般的良好实践,你应该对模块中的所有对话服务使用providedIn: SomeModule。

将此添加到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中。

如果您仍然没有解决这个问题-像我一样-这是导致我这个错误的原因。正如@jkyoutsey所建议的,我确实在尝试创建一个模态组件。根据他的建议,我花了相当多的时间将我的组件移动到一个服务并将其注入到页面组件中。还将providedIn: 'root'更改为MyModule,当然必须至少向上移动一级以避免循环引用。我不确定这些是否真的有必要。

最终解决8个小时难题的是在我的组件中不实现ngOnInit。我盲目地实现了ngOnInit,即使函数是空的。我倾向于那样做。这可能是一个不好的做法。

无论如何,如果有人能解释为什么空的ngOnInit会导致这个错误,我很乐意阅读评论。

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

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

例如:

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

如果在entryComponents中提供组件对话框类后仍然有错误,请尝试重新启动ng serve -这对我来说是有效的。