angular2/4。内置FormsModule时,我应该使用Reactive Forms做什么?

angular2/4. What for should I use Reactive Forms when there is built in FormsModule?

谁能解释一下为什么 我需要使用它们吗?

在哪些情况下,与 FormsModule 相比,Reactive Forms 让我的生活更简单、更好?

Reactive Forms 和 Forms Module 都是完全可以接受的,基于你的 need.In Reactive Forms(Model Driven Forms) 你可以在你的组件上定义你的字段和验证,并将它们连接到你的 html template.It 需要额外的代码,但它有一些优点。

例如,您可以根据代码中的决定更动态地构建表单和验证。

另一个巨大的好处是它使您的所有验证逻辑单元都可测试

基本上,如果你的需求很简单,FormsModule就足够了。我的第一个表格都是FormsModule。如果您只需要将表单输入绑定到模型属性,它们就很棒。

ReactiveFormsModule 是您第一次设置时比较痛苦的地方,但它们给了您更多的控制权。因为您在组件中创建表单元素,所以您可以轻松地执行以下操作:

  • read/write 任何时候输入的值(甚至在构建视图之前)
  • 定义高级验证规则,包括异步验证器(例如:在用户填写注册表的其余部分时,检查服务器输入的用户名是否可用)
  • 当值发生变化时得到通知并立即做出反应
  • 访问原生HTML表单元素
  • 重置表单...
  • 如果您关心单元测试(优秀的编码人员应该关心),反应式形式更容易测试,因为它们可以命令式操作。使用 FormsModule,仅在单元测试中获取对表单实例的引用是一件痛苦的事情。

自从我切换后,我还没有回到 FormsModuleSee the docs

Angular reactive forms facilitate a reactive style of programming that favors explicit management of the data flowing between a non-UI data model (typically retrieved from a server) and a UI-oriented form model that retains the states and values of the HTML controls on screen. Reactive forms offer the ease of using reactive patterns, testing, and validation.

With reactive forms, you create a tree of Angular form control objects in the component class and bind them to native form control elements in the component template, using techniques described in this guide.

You create and manipulate form control objects directly in the component class. As the component class has immediate access to both the data model and the form control structure, you can push data model values into the form controls and pull user-changed values back out. The component can observe changes in form control state and react to those changes.