Angular 14 typed forms - initial value for number controls

Viewed 218

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.

2 Answers

You could set it to 0 if you don't need to display that number... You could also set a second type undefined or null but it's basically like having nonNullable at false.

Here's an example:

public formControl: FormControl<number | undefined> = new FormControl<number | undefined>(undefined);

There nothing wrong to allow null. In fact you should use it if your initial value is not set. You'll have better intellisense in you html and typescript. It will help you prevent access to undefined variable (ex: user is undefined, so user.name will throw an error, forcing you to use user?.name).

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.

Related