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;