0

我可以用这个方法来创建动态组件:角2动态组件生成,TS编译错误

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; 
    } 

,并调用它是这样的:

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

但打字稿把我这个编译错误: app.component.ts:45:35 Untyped function calls may not accept type arguments.

我试图用Type<T>代替{new(): T}但我有同样的错误:app.component.ts:45:35 Untyped function calls may not accept type arguments.

这里的正确定义是什么?因为代码的工作很大...

编辑:这里是完整的代码,如果你想看到它在的地方https://github.com/jaumard/ng2-dashboard/blob/master/components/dashboard/dashboard.component.ts#L99

回答

1

我设法通过改变签名修复编译错误:

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

而这样的呼叫:

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