角强型反应形式 [英] Angular strongly typed reactive forms

查看:83
本文介绍了角强型反应形式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望在Angular项目中重构大量组件,使其具有强类型的FormGroups,FormArrays和FormControls.

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?

谢谢.

通过强类型进行澄清,当前是指我在创建FormGroup或FormArray时无法指定其中的实际表单的结构.当我将此表单传递给应用程序中的各个组件时,我感到维护起来更加困难.

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.

推荐答案

最优雅的解决方案是利用TypeScript声明文件(*.d.ts)引入通用接口,以扩展标准形式类,例如AbstractControlFormControl等.它没有引入任何新功能,并且在已编译的JavaScript中没有占用空间,但是同时强制执行强类型检查.

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.

这是Daniele Morosinotto在今年3月提出的建议,并且现在有讨论将其包含在Angular 9中.

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

采用解决方案很简单:

  1. 此要点下载TypedForms.d.ts并将其另存为src/typings.d.ts在您的项目中( Angular 6+已经知道如何使用此文件.
  2. 每当需要强类型验证时就开始使用新类型(FormGroupTyped<T>FormControlTyped<T>等)(请参见要点 stackblitz ).
  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.

这篇关于角强型反应形式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆