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

其他回答

我在使用动态组件的ag网格中遇到了同样的问题。我发现你需要在ag-grid模块中添加动态组件。withcomponents []

进口:[ StratoMaterialModule, BrowserModule, AppRoutingModule, HttpClientModule, BrowserAnimationsModule, NgbModule.forRoot (), FormsModule, ReactiveFormsModule, AppRoutingModule, AgGridModule.withComponents (ProjectUpdateButtonComponent) ],

你应该像这样在模块中导入NgbModule:

@NgModule ({ 声明:[ AboutModalComponent ], 进口:[ CommonModule, SharedModule, RouterModule, FormsModule, ReactiveFormsModule, NgxLoadingModule, NgbDatepickerModule, NgbModule ], entryComponents (AboutModalComponent): }) 导出类HomeModule {}

我的错误是在.html中调用NgbModal open方法时参数不正确

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

entryComponents:[ConfirmComponent],

以及声明:

declarations: [
    AppComponent,
    ConfirmComponent
]

参见entryComponent的详细信息:

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

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