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

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

问题描述

我希望重构我的 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) 引入扩展标准表单类的通用接口,例如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. 在需要强类型验证时开始使用新类型(FormGroupTypedFormControlTyped 等)(请参阅 那个要点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.

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

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