Angular Tips — Use nonNullable: true to restore default values on reset

Nhan Nguyen
1 min readFeb 6, 2024

--

Form controls and groups are nullable by default in Angular, which means that the following example of FormControl value is not of type string:

normalFormControl = new FormControl('normal@sample.com')

If we try to read normalFormControl.value, we will see that the type is string or null. Why would that be the case since we have a default value? That is because the form can be reset with an on the form or by calling normalFormControl.reset(), for instance.

The trick to make that control non-nullable by adding the following option:

defaultValueFormControl = new FormControl('default.value@sample.com', {
nonNullable: true,
})

Now, when the form gets reset, defaultValueFormControl.value is equal to default.value@sample.com, which is perfect in several different form scenarios, such as an edit form, where we do not want to lose the previous values but just reset to those values.

An example is here

I hope you found it useful. Thanks for reading. 🙏

Let’s get connected! You can find me on:

--

--