How to Specify an Angular FormControl as Non-Nullable and Also Include Validation with Typed Forms
I recently upgraded a project to Angular 14. It's been a long running project, created using Angular 4 (I think), and even though I've been upgrading the version of Angular as new versions are released, I only recently learned that the tsconfig.json settings were the same as they'd been when the project was created, so I took the opportunity to bring those up to the current standards as well.
Unfortunately, with the stricter template type-checking in place, some of my existing code no longer compiled. I figured that this would be a great time to switch over to the new Typed Forms introduced in Angular 14.
One thing that threw me off a bit was how I could create a FormControl that doesn't allow nulls, but that also includes validation. The official docs mention supplying the nonNullable option, but I was confused as to how I could also include my regular validation functions as there didn't seem to be an overload that supported that. But by digging a little deeper, I found that the same option that contains the nonNullable option also includes a property for specifying your validation functions. Here's an example which includes both specifying a single validator and multiple validators (I'm not including the entire FormGroup below, only the stuff you're interested in):
And that did the trick. As Typed Forms are new, the documentation is a little sparse right now, but it gives a good enough introduction, and anything else you might need to figure out can hopefully be found by diving into the TypeScript definitions.
Comments
Post a Comment