[英]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.