I have edited the official Angular.io tutorial on Dynamic Forms, in order to add a form control/input field of type "number".
https://plnkr.co/edit/NslBCrFZLQnLblAqcmzV
NumberQuestion class
import { QuestionBase } from './question-base';
export class NumberQuestion extends QuestionBase<string> {
controlType = 'numberbox';
type: string;
constructor(options: {} = {}) {
super(options);
this.type = options['type'] || '';
}
}
Creating a new NumberQuestion :
//...
new NumberQuestion({
key: 'years',
label : 'Years active',
type : 'number',
order : 4
})
Template :
<div [formGroup]="form">
<label [attr.for]="question.key">{{question.label}}</label>
<div [ngSwitch]="question.controlType">
<input *ngSwitchCase="'textbox'" [formControlName]="question.key"
[id]="question.key" [type]="question.type">
<input *ngSwitchCase="'numberbox'" [formControlName]="question.key"
[id]="question.key" [type]="question.type">
<select [id]="question.key" *ngSwitchCase="'dropdown'" [formControlName]="question.key">
<option *ngFor="let opt of question.options" [value]="opt.key">{{opt.value}}</option>
</select>
</div>
<div class="errorMessage" *ngIf="!isValid">{{question.label}} is required</div>
</div>
If you click on the Load Defaults button, and then the Save button you will see that the form's value object, preserves the numeric type of the formControl 'Years active'.
But if you firstly type inside the 'Years active' control and then hit Save, you will see that the value has been transformed to string.
I understand that this is normal behavior, as described here : https://stackoverflow.com/a/35791893/2025271
I would like to know if there is a way to instruct Angular's FormControl to preserve number type inputs as "numbers", when accessing their value.
I know that i can do this manually, by using parseInt() to edit value on change, but i am trying to find if there is a built in way to do it.