如何在angular 2组件中传递泛型类型并创建此类型的实例
如何在Angular 2/Typescript中创建能够创建泛型类型实例的泛型组件如何在angular 2组件中传递泛型类型并创建此类型的实例,angular,typescript,Angular,Typescript,如何在Angular 2/Typescript中创建能够创建泛型类型实例的泛型组件 @Component({ selector: 'generic', template: 'generic.html' }) export class GenericComponent<T> { private array: T[]; addElement() { const object = new T(); this.array.pu
@Component({
selector: 'generic',
template: 'generic.html'
})
export class GenericComponent<T> {
private array: T[];
addElement() {
const object = new T();
this.array.push(object);
}
}
@组件({
选择器:“通用”,
模板:“generic.html”
})
导出类GenericComponent{
专用数组:T[];
附加元素(){
const object=new T();
this.array.push(对象);
}
}
目前我收到一条错误消息,上面说:
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
}
}
导出类GenericComponent{
//将T的构造函数转换为组件构造函数
构造函数(私有构造函数:new()=>T{}
专用数组:T[];
附加元素(){
const object=newthis.ctor();
this.array.push(对象);
}
}
类项{}
类ItemComponent扩展了GenericComponent{
构造函数(){
super(Item)//传入具体类型的构造函数
}
}
工作解决方案可以是:
@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 {}
@组件({
选择器:“通用”,
模板:“generic.html”
})
导出类GenericComponent{
专用数组:T[];
@Input()创建者:{new():T;};
附加元素(){
const object=新建this.creator;
this.array.push(对象);
}
}
@组成部分({
选择器:'父',
模板:“”
})
导出类ParentComponent{
私有数组:项[];
@Input()itemCreator:{new():Item;};
构造函数(){
this.itemCreator=项目;
}
恩戈尼尼特(){
this.someArray=[];
}
}
类项{}
在这种情况下,我应该能够对所有类似数组的对象使用泛型组件。Hi的可能副本,我一直在思考如何在不使用DI机制的情况下指定T的构造函数。@BartHeyrman您可以创建一个派生类,如上面的示例所示,并使用它,我不认为有一种简单的方法可以直接使用通用组件。我在刚才发布的答案中至少找到了一个可行的解决方案。