6

The value I get on submitting a form group is

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

What I want is

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

My form group is as follows in my .ts file

myForm : FormGroup;
this.myForm = this._formbuilder.group({
  name: [''],
  age: [null]
});
Philipp Kief
  • 6,152
  • 4
  • 32
  • 40
Sunil Behera
  • 126
  • 1
  • 1
  • 7
  • 6
    `+this.myForm.get('age').value` . Use `+` to cast in number – Florian Dec 03 '18 at 09:40
  • Thanks. It worked. Is there no inbuilt way for angular to using validators or something? – Sunil Behera Dec 03 '18 at 11:13
  • 1
    you can add validator on every control, you can `import { Validators } from '@angular/forms'`. For example, if you want the control to be required, you can add an array of validators while you build your form`name: ['', [Validators.required]]`. The best way is to check documentation : https://angular.io/api/forms/Validators try to implement it and open a specific question if you can't make it – Florian Dec 03 '18 at 12:16
  • @Floiran where should I add this line on the code? – zodiac645 Feb 22 '20 at 08:51

2 Answers2

10

Convert it before sending it.

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

Or you can use an input of type number.

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

This just another solution power by rxjs , simply convert input string value to number value on valueChanges

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

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

stackblitz demo

malbarmavi
  • 18,795
  • 4
  • 45
  • 73