[英]How to pass a generic type and create instance of this type in angular 2 component
How can I create a generic component in Angular 2/Typescript that is capable of creating an instance of the generic-type? 如何在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);
}
}
Currently I get an error message saying: 目前,我收到一条错误消息:
TS2693: 'T' only refers to a type, but is being used as a value here.
TS2693:“ T”仅表示类型,但在此处用作值。
Furthermore, I should be able to specify the type somehow: 此外,我应该能够以某种方式指定类型:
<generic ...></generic>
Generics are erased at compile-time so you can't use the type argument T
to create a new instance of T
. 泛型在编译时被擦除,因此您不能使用类型参数
T
创建新的T
实例。 You can however pass is a constructor of T
to the class: 但是,您可以将
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
}
}
A working solution can be: 一个有效的解决方案可以是:
@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 {}
In this case, I should be able to use the generic-component for all array-like objects. 在这种情况下,我应该能够对所有类似数组的对象使用通用组件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.