DEV Community

Nhan Nguyen
Nhan Nguyen

Posted on

1

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:

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay