问题描述
我希望重构我的 Angular 项目中的大量组件,以拥有强类型的 FormGroup、FormArray 和 FormControl.
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
) 引入扩展标准表单类的通用接口,例如AbstractControl
、FormControl
等.它没有引入任何新功能并且在编译的 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.
采用解决方案很简单:
- 从这个要点下载
TypedForms.d.ts
并保存它在你的项目中作为src/typings.d.ts
(Angular 6+ 已经知道如何使用这个文件). - 在需要强类型验证时开始使用新类型(
FormGroupTyped
、FormControlTyped
等)(请参阅 或 stackblitz).
- Download
TypedForms.d.ts
from this gist and save it assrc/typings.d.ts
in your project (Angular 6+ already knows how to use this file). - 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.
这篇关于Angular 强类型反应形式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!