[英]Typescript generic class as Angular2 component
Is it possible to use Typescript template/generic class as Angular2 component? 是否可以将Typescript模板/泛型类用作Angular2组件? If yes, could you give me/point me to a sample code please?
如果是的话,你能给我/给我一个示例代码吗?
Elaborating my question futher: I want to display multiple lists in my application. 再次阐述我的问题:我想在我的应用程序中显示多个列表。 They are visually/functionally same but basically lists of different types for example,
IFruits
, IVegetables
, IGrains
, etc. So, I've been thinking of making a component somewhat like this: 它们在视觉上/功能上相同,但基本上是不同类型的列表,例如
IFruits
, IVegetables
, IGrains
等。所以,我一直在考虑制作一个像这样的组件:
@Component({
selector: 'my-list-display',
})
export class MyListDisplayComponent<T> {
private list: T[];
// further code to display and perform operations on list...
}
Does it even makes sense? 它甚至有意义吗? Is there an alternative to achieving this?
有没有替代实现这一目标? Please enlighten me!
请赐教!
If you want to indicate that the property list
is one of a selection of types, there are a few options I know of. 如果要表明属性
list
是选择的类型之一,我知道有几个选项。 You could create an interface like ListItem
which multiple classes implement. 您可以创建一个类似于
ListItem
的接口,多个类实现该接口。 You could also create an abstract class ListItem
which multiple classes either extend
/ implement
. 您还可以创建一个
abstract class ListItem
,其中多个类可以extend
/ implement
。 For example 例如
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...
}
Using an interface would be similar 使用界面将是类似的
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...
}
If the Fruit
class is actually FruitComponent
, usage is the same (ie FruitComponent implements ListItem
) 如果
Fruit
类实际上是FruitComponent
,则用法是相同的(即FruitComponent implements ListItem
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.