0

I want to create a component in angular 2 that will take some input parameters.I am little bit confused about what should I use class or interface for input and why??For the following component I have used interface

import { Component, Input, Output, EventEmitter } from "@angular/core";

@Component({
  moduleId: module.id,
  selector: 'combo-compo',
  template: `
      <select name="theme" class="form-control" [ngModel]="selectedObject" (ngModelChange)="onChangeObj($event)">
        <option [ngValue]="theme" *ngFor="let theme of dataObject" >{{theme.value}}</option>
      </select>
            `
})

export class ComboComponent {
  selectedObject: ComboInterface;
  @Input() dataObject: Array<ComboInterface>;
  @Output() onComboChange = new EventEmitter();

  onChangeObj(newObj: ComboInterface) {
    this.selectedObject = newObj;
    this.onComboChange.emit(this.selectedObject);
  }

}

interface ComboInterface {
    key: string;
    value: string;
}
Keshav
  • 821
  • 2
  • 12
  • 33
  • In the case of `@Input`, I think it's more practical to use `interface` rather than `class` – Abrar Jun 16 '17 at 10:26

2 Answers2

2

In Typescript, you are free to use either of CLASS or INTERFACE.

Below are the reasons which can help you take the right decision in choosing the correct structure:

Interface: You can only declare your properties with its corresponding type. This means you cannot have functions in it, nor those properties can be initialized at the time of declaration.

Class: You can declare your properties along with a default value and also with the functions.

PS: Interfaces are preferred over classes when you just want the structure of the data

Sashi Kant
  • 13,277
  • 9
  • 44
  • 71
1

Interfaces are preferable to classes as they are more flexible, and any class could implement that interface and be used for the input. Also, if you are unit testing you can create mock or stub classes that implement the interface so that you can test your components in isolation.

Although, in practical terms, if you only ever have one class that implements this interface, and it isn't used anywhere else, then there probably isn't the need to go the extra step of creating an interface, and you should maybe just us a class.

Dean Chalk
  • 20,076
  • 6
  • 59
  • 90