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

其他回答

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

  "angularCompilerOptions": {
    "enableIvy": false
  }

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

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。

我对引导模态也有同样的问题

从 '@ng-bootstrap/ng-bootstrap' 导入 { NgbModal };

如果是这种情况,只需像其他响应建议的那样,将组件添加到模块声明和entryComponents中,但也要将此添加到模块中

import { NgbModule } from '@ng-bootstrap/ng-bootstrap';

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

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

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

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

 entryComponents: [
CityModalComponent
],