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

我该怎么解决呢?


当前回答

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

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

其他回答

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

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

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

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

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

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

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

例如:

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

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

    entryComponents: [
    TreatListComponent,
    MyTreatComponent
  ],

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。

将该组件添加到应用模块的@NgModule的entryComponents中:

entryComponents:[ConfirmComponent],

以及声明:

declarations: [
    AppComponent,
    ConfirmComponent
]