虽然这个话题已经在其他职位这样的讨论:打字稿及角反射2
Dynamically loading a typescript class (reflection for typescript)
我无法找到一个答案,我的具体问题。所以,如果这是重复的,请原谅我。
我想在Angular 2(使用Typescript)中创建一个非常简单的指令,它允许动态添加或删除一组由Type代表的控件。例如,如果类型是:
class Stone{
constructor(
public nameOfStone?: string,
public typeOfStone?: string
){}
}
的UI将有这样的事情:
我能够获得与特定类型(例如:石)这方面的工作。但是,鉴于指令的目的只是添加这个动态添加/删除功能,我觉得参数化要创建的类型并将其用于不同的类型定义是有意义的。我试图在Component类是这样的:
import {Component} from 'angular2/core';
import {NgForm} from 'angular2/common';
import {ControlGroup, Control, FormBuilder, FORM_DIRECTIVES} from 'angular2/common'
@Component({
selector: 'stone-details',
templateUrl: '../stones/stone-details.component.html',
directives: [FORM_DIRECTIVES]
})
export class StoneComponent {
type = 'Stone';
Stones = new Array<Stone>();
addBtnClicked(){
let Stone = Object.create(window['Stone'].prototype);
//let Stone = new Stone('', '');
this.Stones.push(Stone);
}
removeBtnClicked(index: number){
if(index >= this.Stones.length){
alert('Not a valid index');
}else if(confirm('Remove this Stone?')){
this.Stones.splice(index, 1);
}
}
}
class Stone{
constructor(
public nameOfDeity?: string,
public typeOfDeity?: string
){}
}
当我使用注释行 let Stone = new Stone('', '');
部件完美地工作,但如果我用 let Stone = Object.create(window['Stone'].prototype);
它似乎并没有工作,我看到的错误是 angular2.dev.js:23941 ORIGINAL EXCEPTION: TypeError: Cannot read property 'prototype' of undefined
。
我最初认为导出Stone类会有帮助,但没有一个疯狂的变体(导出类,试图将该类引用为window ['StoneComponent'] .portal_1 ['Stone'])帮助。我知道该组件并不直接在窗口组件下可见,但我不确定我错过了什么。有没有其他方法可以做到这一点?我错过了什么吗?请指教。
P.S:我正在使用Angular 2和Typescript的最新版本(几天前我开始使用这个应用程序)。
'Object.create(Stone.prototype)'不工作? – jpopesculian
它的确如此,但我无法让它变成动态的。也就是说,Object.create(Stone.prototype)的作品,与Stone = new Stone()并没有多大区别。但是我无法使用变量代替Stone类型,例如:Object.create( .prototype) –
user1452030
这很困难,因为它很难知道父对象是什么。我猜不是它的窗户。你尝试过'这个'吗?否则,您可以创建自己的可能的原型字典,然后通过该字典访问原型(似乎足够安全,您只需要维护它)。否则,可以尝试'eval(“Stone”)'?虽然 – jpopesculian