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):

    this.exerciseForm = this._formBuilder.group<IExerciseEditForm>({
      id: new FormControl<number>(0, { nonNullable: true, validators: Validators.required }),
      name: new FormControl<string>('', { nonNullable: true, validators: Validators.required }),
      description: new FormControl<string>('', { nonNullable: true,
validators: Validators.compose([Validators.required, Validators.maxLength(4000)])}),

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

Popular Posts

Resolving the "n timer(s) still in the queue" Error In Angular Unit Tests

How to Get Norton Security Suite Firewall to Allow Remote Desktop Connections in Windows

How to Determine if a Column Exists in a DataReader

Silent Renew and the "login_required" Error When Using oidc-client

Fixing the "Please add a @Pipe/@Directive/@Component annotation" Error In An Angular App After Upgrading to webpack 4