动态创建TypeScript对象

时间:2016-09-14 12:04:26

标签: javascript angular typescript

关于a post关于在TypeScript中动态创建对象的问题,我将以下代码用作工厂从其名称创建对象:

public createComponent(context: Object, componentName: string): ComponentRef<ComponentBase> {
    this.viewContainer.clear();
    var instance = 
        Object.create(context[componentName].prototype); // <-- fails
    let componentFactory =
            this.componentFactoryResolver.resolveComponentFactory(instance);
    return <ComponentRef<ComponentBase>> this.viewContainer.createComponent(componentFactory);
}

我并不完全相信我理解这种window[suchAndSuch]语法:它是什么意思?找不到任何文档。

无论如何,window[myClassName]似乎未定义,即使相关类在同一文件中定义。我查看了从TypeScript中编译的Javascript,并且有问题的类在范围内。

我想。

帮助!

- 更新 - 我有这个代码,它是Angular 2应用程序的一部分,它调用上面的方法来尝试获取组件的实例,注入和所有:

export class CustomUserComponent implements OnChanges {
    @Input() componentType: string;
    @ViewChild(ComponentDirective) componentAnchor: ComponentDirective;
    ref: ComponentRef<GalleriaComponentBase>;

    ngAfterViewInit() {
        this.ref = this.componentAnchor
            .createComponent(window, this.componentType);
    }
}

0 个答案:

没有答案