Typescript generic class as Angular2 component

Can Typescript template / generic class be used as Angular2 component? If yes, could you please give me / point me to some example code?

Developing my question: I want to display multiple lists in my application. They visually / functionally the same, but in the main list of different types, such as IFruits

, IVegetables

, IGrains

, etc. So, I was thinking about creating a component something like this:

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

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

      

Does it even make sense? Is there any alternative to this? Please enlighten me!

+3


source to share


1 answer


If you want to indicate that a property list

is one of several types, there are several options that I am aware of. You can create an interface of a type ListItem

that is implemented by multiple classes. You can also create abstract class ListItem

in which multiple classes are either 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 the interface will 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 class is Fruit

in fact FruitComponent

, using the same (i.e. FruitComponent implements ListItem

)

0


source







All Articles