0

I need to load components dynamically to view on some button click. I have created on directive and some components in my custom module. But when I try to create new instance of component it says No component factory found.

Here is my code structure.

dashboard module

 @NgModule({
      declarations: [MainPageComponent, WidgetComponent, ChartsComponent, GraphsComponent, InfographicsComponent, InsertionDirective],
      imports: [
        CommonModule,
        GridsterModule,
        ButtonsModule,
        ChartsModule,
        DropDownsModule
      ],
      entryComponents: [MainPageComponent, WidgetComponent, ChartsComponent, GraphsComponent, InfographicsComponent],
      exports: [MainPageComponent, WidgetComponent, ChartsComponent, GraphsComponent, InfographicsComponent]
    })
    export class DashboardModule {
      static customization(config: any): ModuleWithProviders {
        return {
          ngModule: DashboardModule,
          providers: [
            { provide: Service, useClass: config.service }
          ]
        }
      }
    }

dashboard/insert directive

import { Directive, ViewContainerRef } from '@angular/core';

@Directive({
  selector: '[appInsertion]'
})
export class InsertionDirective {

  constructor(public viewContainerRef: ViewContainerRef) { }
}

1. dashboard/mainMainPageComponent.ts

 import { Component, OnInit, ViewChild, ComponentFactoryResolver, ComponentRef, Type } from '@angular/core';
        import { Service } from 'src/app/services/service';
        import { Widget } from 'src/app/interface/widget';
        import { GridsterConfig, GridsterItem } from 'angular-gridster2';
        import { SETTINGS } from '../settings'
        import { InsertionDirective } from '../insertion.directive';
        import { ChartComponent } from '@progress/kendo-angular-charts';


        @Component({
          selector: 'dasbhoard-main-page',
          templateUrl: './main-page.component.html',
          styleUrls: ['./main-page.component.css']
        })
        export class MainPageComponent implements OnInit {
          componentRef: ComponentRef<any>;
          childComponentType: Type<any>;
          @ViewChild(InsertionDirective)
          insertionPoint: InsertionDirective;

          public title: string;
          public widgets: Array<{ widget: Widget, grid: GridsterItem, type: string }> = [];
          public options: GridsterConfig;

          constructor(private service: Service, private componentFactoryResolver: ComponentFactoryResolver) {
            this.title = 'Dashboard';
          }


          ngOnInit() {
            this.options = {
              itemChangeCallback: MainPageComponent.itemChange,
              itemResizeCallback: MainPageComponent.itemResize,
            };

          }
          addNewWidget(type: string) {
            let widgetType = SETTINGS.widgetSetting[type];
            let totalWidgets = this.widgets ? this.widgets.length : 0;

            let componentFactory = this.componentFactoryResolver.resolveComponentFactory(widgetType.useClass);
//widgetType.useClass = ChartsComponent
// when I pass it statically its ok 
            //error here 
            let viewContainerRef = this.insertionPoint.viewContainerRef;
            viewContainerRef.clear();
            this.componentRef = viewContainerRef.createComponent(componentFactory);

            this.widgets.push({ widget: { id: totalWidgets, header: `Widget ${totalWidgets} Header`, content: `<h1>Widget ${totalWidgets} Body</h4>` }, grid: { cols: 1, rows: 1, x: 0, y: 0 }, type: type });

          }
        }

dashboard/main-component/main-component.html

<ng-template appInsertion> </ng-template>     
<button kendoButton(click) = "addNewWidget('charts')"[primary] = "true" class="pull-right" > Add Chart Widget </button>

I have each and every posts and all says you need to insert componets into entry points but I've already included all components to entry points. And all components are inside the same module but still it says no No component factory found for ChartsComponent. Did you add it to @NgModule.entryComponents?.

Any one please can you find out the where I'm doing wrong?

Thanks in advance.

1 Answer 1

1

I think it's just a typo: In entryComponents you've written ChartsComponent and in the resolveComponentFactory method you've written ChartComponent

Could that be it?

Sign up to request clarification or add additional context in comments.

3 Comments

But its only one issue. You can check my code above. When I pass resolveComponentFactory(widgetType.useClass); it shows error but when I do resolveComponentFactory(ChartsComponent); its Ok.
Ok, then I'll remove the last paragraph in my answer. Is everything working now then with the typo corrected?
When I pass the component statically it works but when passing it dynamically it shows the same error. esolveComponentFactory(widgetType.useClass); it shows error but when I do resolveComponentFactory(ChartsComponent) it works.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.