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

我该怎么解决呢?


当前回答

TL;DR: ng6中带有providedIn: "root"的服务在app.module的entryComponents中没有添加组件时,无法找到ComponentFactory。

如果你在使用angular 6的同时在服务中动态创建组件,也会出现这个问题!

例如,创建一个Overlay:

@Injectable({
  providedIn: "root"
})
export class OverlayService {

  constructor(private _overlay: Overlay) {}

  openOverlay() {
    const overlayRef = this._createOverlay();
    const portal = new ComponentPortal(OverlayExampleComponent);

    overlayRef.attach(portal).instance;
  }
}

问题在于

提供于:“根”

定义,它在app.module中提供此服务。

因此,如果你的服务位于,例如,“OverlayModule”中,在那里你也声明了OverlayExampleComponent并将其添加到entryComponents中,该服务无法为OverlayExampleComponent找到ComponentFactory。

其他回答

参见entryComponent的详细信息:

如果你正在动态加载任何组件,那么你需要把它放在declarations和entryComponent中:

@NgModule({
  imports: [...],
  exports: [...],
  entryComponents: [ConfirmComponent,..],
  declarations: [ConfirmComponent,...],
  providers: [...]
})

在导入中添加'NgbModalModule',并在entryComponents App.module.ts中添加组件名称,如下所示

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

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

在我的例子中,我根本不需要entryComponents -只需要下面链接中描述的基本设置,但我需要在主应用程序模块和外围模块中都包含导入。

imports: [
    NgbModule.forRoot(),
    ...
]

https://medium.com/@sunilk/getting-started-angular-6-and-ng-bootstrap-4-4b314e015c1c

如果一个组件将被包含在模态中,你只需要将它添加到entryComponents中。从文档中可以看出:

您可以将现有组件作为模式窗口的内容传递。在 在这种情况下,请记住将内容组件添加为entryComponents 部分。