How do I declare a model class in my Angular 2 component using TypeScript? How do I declare a model class in my Angular 2 component using TypeScript? angular angular

How do I declare a model class in my Angular 2 component using TypeScript?


I'd try this:

Split your Model into a separate file called model.ts:

export class Model {    param1: string;}

Import it into your component. This will give you the added benefit of being able to use it in other components:

Import { Model } from './model';

Initialize in the component:

export class testWidget {   public model: Model;   constructor(){       this.model = new Model();       this.model.param1 = "your string value here";   }}

Access it appropriately in the html:

@Component({      selector: "testWidget",      template: "<div>This is a test and {{model.param1}} is my param.</div>"})

I want to add to the answer a comment made by @PatMigliaccio because it's important to adapt to the latest tools and technologies:

If you are using angular-cli you can call ng g class model and it will generate it for you. model being replaced with whatever naming you desire.


The problem lies that you haven't added Model to either the bootstrap (which will make it a singleton), or to the providers array of your component definition:

@Component({    selector: "testWidget",    template: "<div>This is a test and {{param1}} is my param.</div>",    providers : [       Model    ]})export class testWidget {    constructor(private model: Model) {}}

And yes, you should define Model above the Component. But better would be to put it in his own file.

But if you want it to be just a class from which you can create multiple instances, you better just use new.

@Component({    selector: "testWidget",    template: "<div>This is a test and {{param1}} is my param.</div>"})export class testWidget {    private model: Model = new Model();    constructor() {}}


export class Car {  id: number;  make: string;  model: string;  color: string;  year: Date;  constructor(car) {      {        this.id = car.id;        this.make = car.make || '';        this.model = car.model || '';        this.color = car.color || '';        this.year = new Date(car.year).getYear();      }  }}

The || can become super useful for very complex data objects to default data that doesn't exist.

..

In your component.ts or service.ts file you can deserialize response data into the model:

// Import the car modelimport { Car } from './car.model.ts';// If single objectcar = new Car(someObject);// If array of carscars = someDataToDeserialize.map(c => new Car(c));