Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular strongly typed reactive forms

I'm looking to refactor a large set of components in my Angular project to have strongly typed FormGroups, FormArrays, and FormControls.

I'm just looking for a good way to implement strongly typed reactive forms. Could anyone provide suggestions/recommendations from their own experiences?

Thank you.

EDIT:

To clarify, by strongly typed I mean currently when I create a FormGroup or FormArray I have no way to specify the structure of the actual form inside it. When I pass this form around to various components in my app, I then feel I am making it more difficult to maintain.

like image 253
Tom Vinnicombe Avatar asked Mar 07 '19 21:03

Tom Vinnicombe


People also ask

Is Angular strongly typed?

Angular Reactive Forms are not strongly typed! AbstractControl and it's implementations FormControl , FormGroup and FormArray do not support strong typing their value or changes or any other property/method.

What is typed forms in Angular?

Typed forms enforce a model through which we can access the properties in a uniform way for Angular forms. In the concept of typed form we have the property name and its data type defined. This was not possible in older versions of angular. Prior to Angular 14, we used a loosely typed forms model.

What are reactive forms Angular?

Reactive forms include a set of validator functions for common use cases. These functions receive a control to validate against and return an error object or a null value based on the validation check. Import the Validators class from the @angular/forms package.

Which is better template driven or reactive forms in Angular?

Template Driven Forms are based only on template directives, while Reactive forms are defined programmatically at the level of the component class. Reactive Forms are a better default choice for new applications, as they are more powerful and easier to use.


1 Answers

The most elegant solution is leveraging TypeScript declaration files (*.d.ts) to introduce generic interfaces extending the standard form classes like AbstractControl, FormControl, etc. It doesn’t introduce any new functionality and has no footprint in the compiled JavaScript, but at the same time enforcing strong type checking.

It was suggested by Daniele Morosinotto in March this year and there are talks now to include it in Angular 9.

Adopting the solution is straightforward:

  1. Download TypedForms.d.ts from this gist and save it as src/typings.d.ts in your project (Angular 6+ already knows how to use this file).
  2. Start using the new types (FormGroupTyped<T>, FormControlTyped<T>, etc.) whenever you need a strong type validation (see examples in that gist or stackblitz).

For more information, check out a blog post analysing available solutions for strongly typed forms.

like image 67
Alex Klaus Avatar answered Oct 03 '22 15:10

Alex Klaus