Search code examples
javascriptangulartypescriptunary-operator

Angular Typescript interface of number is set in form validation to null , then unary plus operator throws errors if not set


While I know that there are several ways of setting up angular typescript interfaces and then interacting with them.. This is my problem.

I set the interface

export interface EditUPC {
    weight: number,
    // other fields
}

Then in reactive forms in component

private initForms(fb: FormBuilder){
   upcForm: fb.group({
     
      weight: null,
      // other fields
   })
}

Next with SAVING the form

this line blows up with "Cannot read property of Null" because of the "+" unary operator to convert to number..

 this.upcEdit = 
 {
     weight: +this.form.get('upcForm').get('weight').value,
     //other fields
 }

So while I could write a function or have conditionals on my several numeric fields , is there an easier/better way?


Solution

  • You can convert your form to an object with getRawValue().

    this.upcEdit = upcForm.getRawValue();