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;
}
1
  • In the case of @Input, I think it's more practical to use interface rather than class Commented Jun 16, 2017 at 10:26

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.