如何在角度2组件

时间:2018-06-12 13:27:35

标签: 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.push(object);
    }
}

目前我收到一条错误消息:

  

TS2693:&#39; T&#39;仅指类型,但在此处用作值。

此外,我应该能够以某种方式指定类型:

<generic ...></generic>

2 个答案:

答案 0 :(得分:3)

泛型在编译时被删除,因此您无法使用类型参数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
    }
}

答案 1 :(得分:1)

工作解决方案可以是:

@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 {}

在这种情况下,我应该能够将泛型组件用于所有类似数组的对象。