数字的 Angular Typescript 接口在表单验证中设置为 null ,如果未设置,则一元加运算符会引发错误

问题描述

虽然我知道有几种方法可以设置角度打字稿界面,然后与它们交互..这是我的问题。

我设置了界面

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

然后在组件中以反应形式

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

接下来保存表单

由于要转换为数字的“+”一元运算符,此行因“无法读取 Null 的属性”而爆炸..

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

所以虽然我可以编写一个函数或对我的几个数字字段设置条件,但有没有更简单/更好的方法

解决方法

您可以使用 getRawValue() 将表单转换为对象。

this.upcEdit = upcForm.getRawValue();