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

我该怎么解决呢?


当前回答

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

其他回答

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。

我用的是Angular8,我试着从另一个模块动态地打开这个组件, 在这种情况下,您需要将模块导入到试图打开该组件的模块中,当然,除了导出该组件并将其列出到entryComponents数组中,就像前面的答案所做的那样。

imports: [
    ...
    TheModuleThatOwnTheTargetedComponent,
    ...
  ],

我可能稍后再回复。但是对于那些仍然在寻找这个问题的解决方案并且在他们的代码中有这个的人来说,删除这个可能是有帮助的。我们在tsconfig中有以下条目。json文件:

  "angularCompilerOptions": {
    "enableIvy": false
  }

我们也面临同样的问题。经过大量的实验,我们从tsconfig.json中删除了这个块。现在我们的代码不再抱怨这个问题了。

在本节中,你必须在app.module.ts文件的以下部分中输入作为子组件使用的组件:[CityModalComponent](模态组件):

 entryComponents: [
CityModalComponent
],

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

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

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