Angular 2动态组件生成,ts编译错误

时间:2016-11-16 13:59:34

标签: angularjs angular typescript compilation angular2-components

我可以使用此方法创建动态组件:

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.

我尝试将{new(): T}替换为Type<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 个答案:

答案 0 :(得分:1)

我设法通过将签名更改为:

来修复编译错误
public addItem(ngItem: Type<WidgetComponent>): WidgetComponent

这样的电话:

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