Search code examples
angularjsangulartypescriptcompilationangular2-components

Angular 2 dynamic component generation, ts compilation error


I can create dynamic component by using this method:

public addItem<T extends WidgetComponent>(ngItem: {new(): T}): T {
    let factory = this._componentFactoryResolver.resolveComponentFactory(ngItem);
    const ref = this._viewCntRef.createComponent(factory);
    const newItem: T = ref.instance as T;
    ...
    return newItem;
  }

And call it like this:

const ref: MyWidgetComponent = this.dashboard.addItem<MyWidgetComponent>(MyWidgetComponent);

But typescript put me this compilation error: app.component.ts:45:35 Untyped function calls may not accept type arguments.

I try to replace {new(): T} by Type<T> but I have the same error: app.component.ts:45:35 Untyped function calls may not accept type arguments.

What is the correct definition here ? Because the code work great...

EDIT: here is the full code if you want to see it in place https://github.com/jaumard/ng2-dashboard/blob/master/components/dashboard/dashboard.component.ts#L99


Solution

  • I manage to fix compilation error by changing the signature to :

    public addItem(ngItem: Type<WidgetComponent>): WidgetComponent
    

    And the call like this :

    const ref: MyWidgetComponent = this.dashboard.addItem(MyWidgetComponent) as MyWidgetComponent;