如何在this.formgroup.value()上获取数字类型的值?

时间:2018-12-03 09:36:58

标签: angular typescript-typings formgroups

我提交表单组的价值是

{
  "name": "Sunil",
  "age": "23"
}

我想要的是

{
  "name": "Sunil",
  "age": 23
}

我的.ts文件中的表单组如下

myForm : FormGroup;
this.myForm = this._formbuilder.group({
  name: [''],
  age: [null]
});

2 个答案:

答案 0 :(得分:4)

在发送前将其转换。

const value = { ...this.myForm.value, age: +this.myForm.value.age };

或者您可以使用数字类型的输入。

<input type="number" formControlName="age">

答案 1 :(得分:0)

这是rxjs的另一种解决方案,只需将valueChanges上的输入字符串值转换为数字值

const ageFormControl = this.myForm.get('age');

ageFormControl.valueChanges
  .pipe(distinct())
  .subscribe(value => ageFormControl.setValue(+value));

stackblitz demo