Angular strongly typed reactive forms

时光总嘲笑我的痴心妄想 提交于 2019-12-06 07:25:36

问题


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.


回答1:


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.




回答2:


The solution I ended up using was a library I found called ngx-strongly-typed-forms

It enables you to have strongly typed FormControls, FormGroups, and FormArrays. There are some limitations but it's definitely helped a lot in my project.

You can see the documentation at https://github.com/no0x9d/ngx-strongly-typed-forms



来源:https://stackoverflow.com/questions/55053466/angular-strongly-typed-reactive-forms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!