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 callng 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 model
import { Car } from './car.model.ts';
// If single object
car = new Car(someObject);
// If array of cars
cars = someDataToDeserialize.map(c => new Car(c));
In your case you are having model on same page, but you have it declared after your Component class, so that's you need to use forwardRef
to refer to Class
. Don't prefer to do this, always have model
object in separate file.
export class testWidget {
constructor(@Inject(forwardRef(() => Model)) private service: Model) {}
}
Additionally you have to change you view interpolation to refer to correct object
{{model?.param1}}
Better thing you should do is, you can have your Model
Class define in different file & then import it as an when you require it by doing. Also have export
before you class name, so that you can import it.
import { Model } from './model';