简体   繁体   中英

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

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM