No component factory found. Did you add it to @NgModule.entryComponents?

sungyong picture sungyong · Jul 31, 2017 · Viewed 17.1k times · Source

While using ag-grid with angular4, I'm stuck with below error message.

I'm trying to display row data after fetch json via HTTP.

this.gridOptions.api.setRowData(this.gridOptions.rowData);

But my code made below error message.

ERROR Error: No component factory found for RedComponentComponent. Did you add it to @NgModule.entryComponents?

This is my app module code. I'd already set to entryComponents.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { AgGridModule} from "ag-grid-angular/main";

import { AppComponent } from './app.component';
import { MyGridApplicationComponent } from './my-grid-application/my-grid-application.component';
import { RedComponentComponent } from './red-component/red-component.component';

@NgModule({
  imports: [
    BrowserModule,
    AgGridModule.withComponents(
      [RedComponentComponent]
    ),
    FormsModule,
    HttpModule
  ],
  declarations: [
    AppComponent,
    MyGridApplicationComponent,
    RedComponentComponent
  ],
  entryComponents: [
    RedComponentComponent
  ],  
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

error position of my code

My Question. Why this code can't resolve this component.

Answer

yurzui picture yurzui · Aug 1, 2017

You are passing string to `ComponentFactoryResolver when loading data from server but it should be component type.

header.json

{
  "headerName": "DetailCode",
  "field": "detailCode",
  "cellRendererFramework": "RedComponentComponent", // string
  "width":100
},

to solve it i would create entry components map like:

entry-components.ts

import { RedComponentComponent } from './red-component/red-component.component';

export const entryComponentsMap = {
  'RedComponentComponent': RedComponentComponent
};

and then map loading from json string to component class

comm-code-grid-option.service.ts

private fetchColumnDefs() {
 console.log("fetchColumnDefs()");

 this.http.get(this.API_URI + "resident/header.json").subscribe(
   r => {
     this.gridOptions.columnDefs = r.json();
     this.gridOptions.columnDefs.forEach((x: any) => {
       if (x.cellRendererFramework) {
         x.cellRendererFramework = entryComponentsMap[x.cellRendererFramework];
       }
     });