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 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,
})
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.
I hope you found it useful. Thanks for reading. 🙏
Let's get connected! You can find me on:
- Medium: https://medium.com/@nhannguyendevjs/
- Dev: https://dev.to/nhannguyendevjs/
- Hashnode: https://nhannguyen.hashnode.dev/
- Linkedin: https://www.linkedin.com/in/nhannguyendevjs/
- X (formerly Twitter): https://twitter.com/nhannguyendevjs/
- Buy Me a Coffee: https://www.buymeacoffee.com/nhannguyendevjs
Top comments (0)