2017-04-10 81 views
3

是否可以使用Typescript模板/泛型類作爲Angular2組件? 如果是,請給我/請給我一個示例代碼?Typescript作爲Angular2組件的泛型類

詳細闡述我的問題: 我想在我的應用程序中顯示多個列表。他們是視覺/功能相同,但基本上是不同類型的,例如,IFruitsIVegetablesIGrains等的列表所以,我一直在想使一個組件有點像這樣的:

@Component({ 
    selector: 'my-list-display', 
}) 
export class MyListDisplayComponent<T> { 
    private list: T[]; 

    // further code to display and perform operations on list... 
} 

它甚至是有道理的? 是否有替代方案來實現這一目標? 請賜教!

+0

'通用類爲component'太廣你能具體嗎? – Aravind

回答

0

如果你想表明屬性list是一種選擇類型,我知道有幾個選項。您可以創建多個類實現的接口,如ListItem。您也可以創建一個abstract class ListItem,其中多個類別爲extend/implement。例如

export abstract class ListItem { 
    public name: string; 
} 

export class Fruit implements ListItem { 
    public name: string; 
} 

export class Vegetable extends ListItem { 
} 


@Component({ 
    selector: 'my-list-display', 
}) 
export class MyListDisplayComponent { 
    private list: ListItem[]; 

    // further code to display and perform operations on list... 
} 

使用的界面將類似

export interface ListItem { 
    name: string; 
} 

export class Fruit implements ListItem { 
    public name: string; 
} 

@Component({ 
    selector: 'my-list-display', 
}) 
export class MyListDisplayComponent { 
    private list: ListItem[]; 

    // further code to display and perform operations on list... 
} 

如果Fruit類實際上FruitComponent是,用法是一樣的(即FruitComponent implements ListItem