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

nhannguyendevjs

Nhan Nguyen

Posted on February 6, 2024

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

Image description

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')
Enter fullscreen mode Exit fullscreen mode

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 a 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,
})
Enter fullscreen mode Exit fullscreen mode

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:

πŸ’– πŸ’ͺ πŸ™… 🚩
nhannguyendevjs
Nhan Nguyen

Posted on February 6, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related