I am working on an Angular application, where I have defined some large custom form objects type using interfaces in Typescript. The property types are mostly stringor number.
I am using these object to fill a form using ngModel and therefore I need to assign default values to the properties of this object on the component side (otherwise, it gives error saying that object is undefined).
My question is what is a preferred or good way of assigning default values to the properties of these objects. I am aware of following ways:
- Use interface to define the shape of the object and assign a default value on the component side (Currently, I am following this.)
- Use
Classto define the object and assign a default value in the constructor. By this way, you don't have to worry about assigning default values on the component. I think this is a cleaner way of writing your component code. Not sure though as this is preferred way.
Let me know if using class is preferred a way to define complex objects (with nested properties) when using that object with ngModel. Also, if there are other ways to solve this issue.
ngModeldoes not require all inputs to have default values. Inputs can be left unfilled. So why do you feel you must have default values? Why not make the interface properties optional in the first place?interface(JSON object is not a function, hence doesnt match with a class technically...) and thenuse a serviceto get default instance of that interface (which would work like a constructor (don't do it in component, you will have to do it everytime)