[英]How to pass a generic type and create instance of this type in angular 2 component
如何在Angular 2 / Typescript中创建能够创建泛型类型实例的泛型组件?
@Component({
selector: 'generic',
template: 'generic.html'
})
export class GenericComponent<T> {
private array: T[];
addElement() {
const object = new T();
this.array.push(object);
}
}
目前,我收到一条错误消息:
TS2693:“ T”仅表示类型,但在此处用作值。
此外,我应该能够以某种方式指定类型:
<generic ...></generic>
泛型在编译时被擦除,因此您不能使用类型参数T
创建新的T
实例。 但是,您可以将T
的构造函数传递给该类:
export class GenericComponent<T> {
// Take the constructor of T to the component constructor
constructor(private ctor: new ()=> T) {}
private array: T[];
addElement() {
const object = new this.ctor();
this.array.push(object);
}
}
class Item {}
class ItemComponent extends GenericComponent<Item>{
constructor(){
super(Item) // Pass in the constructor of the concrete type
}
}
一个有效的解决方案可以是:
@Component({
selector: 'generic',
template: 'generic.html'
})
export class GenericComponent<T> {
private array: T[];
@Input() creator: { new (): T; };
addElement() {
const object = new this.creator;
this.array.push(object);
}
}
@Component({
selector: 'parent',
template: '<generic [creator]="itemCreator" [array]="someArray"></generic>'
})
export class ParentComponent {
private someArray: Item[];
@Input() itemCreator: { new (): Item; };
constructor() {
this.itemCreator = Item;
}
ngOnInit() {
this.someArray = [];
}
}
class Item {}
在这种情况下,我应该能够对所有类似数组的对象使用通用组件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.