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:

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay