1

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 Class to 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.

5
  • ngModel does 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? Commented Jun 25, 2017 at 4:15
  • does your objects work without default values aside from filling form? for example, do they work in business logic terms? you didnt give too much details but since your main concern is filling the form it feels like you should set defaults on component side. Commented Jun 25, 2017 at 4:15
  • 1
    use interface (JSON object is not a function, hence doesnt match with a class technically...) and then use a service to 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) Commented Jun 25, 2017 at 4:40
  • @BeetleJuice Only If I make some properties optional in the interface..I can make some input unfilled and does not need to provide default values..is that correct? Commented Jun 26, 2017 at 15:35
  • right if the properties are optional, the compiler won't complain when they're missing Commented Jun 26, 2017 at 15:44

1 Answer 1

2

I have a method like this in my service:

initializeProduct(): IProduct {
    return {
        id: 0,
        productName: null,
        productCode: null,
        tags: [''],
        releaseDate: null,
        price: null,
        description: null,
        starRating: null,
        imageUrl: null
    };
}
Sign up to request clarification or add additional context in comments.

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.