Typed forms are great but I wonder how to initially display a form control with type 'number' as empty input field. I would like to keep my controls as nonNullable as they are required in my form but it excludes using null as initial value which was a solution before.
EDIT: Maybe I describe my case. I have several FormControls of type number. I would like initially to display these inputs empty. So the possible solution is to set initial value in FormControl constructor to null. But then the FormControl has type <number | null>. All of them are required. After submiting I need to send that data to server and asigne a FormControl<number | null> value to property of type number which makes me to add explicit casting to for every property even if I know that after submiting they can't be null because of 'required' validator. I case of FormControl<string> casting isn't necessary and I can display empty input by providing "" as inital value. I was wondering if there is some workaround to do that with number.
The required validator doesn't disallow the input to have an empty value. It just adds the error to the FormControl
, but the value can still be empty. So having <number | null>
makes more sense than <number>
. When the validation passes, you can, at this point, assert that the value is not null with !
(e.g. form.controls.name.value!
). But maybe you should actually have a <string>
type (and pass empty string for the initial value), since an HTML input cannot have a numeric value? If you pass a numeric value to <input type="number">
, the number will be converted to string under the hood. When you retrieve the value from a form, the value is a string, not a number.