From 129f69c3bce23a39cc3a29c77d73dd13871b56f0 Mon Sep 17 00:00:00 2001 From: Brandon Roberts Date: Fri, 24 Aug 2018 11:12:34 -0500 Subject: [PATCH] docs: add forms overview guide (#25663) PR Close #25663 --- aio/content/guide/forms-overview.md | 235 ++++++++++++++++++++++++++++ aio/content/guide/reactive-forms.md | 47 +----- aio/content/navigation.json | 17 +- 3 files changed, 247 insertions(+), 52 deletions(-) create mode 100644 aio/content/guide/forms-overview.md diff --git a/aio/content/guide/forms-overview.md b/aio/content/guide/forms-overview.md new file mode 100644 index 0000000000..86191e204f --- /dev/null +++ b/aio/content/guide/forms-overview.md @@ -0,0 +1,235 @@ +# Forms in Angular + +Handling user input with forms is the cornerstone of many common applications. You use forms to log in to a page, updating a profile, entering sensitive information, and many other data-entry tasks. + +Angular provides two different approaches to handling user input through forms: Reactive and template-driven. Each set of forms promote a distinct way of processing forms and offers different advantages. The sections below provide a comparison of the two approaches and when each one is applicable. There are many different factors that influence your decision on which approach works best for your situation. Whether you’re using reactive or template driven forms, these concepts are key to understanding the mechanisms underneath each solution. + +In general: + +* **Reactive forms** are more robust: they are more scalable, reusable, and testable. If forms are a key part of your application, use reactive forms. +* **Template-driven forms** are useful for adding a simple form to an app, such as a single email list signup form. They are easy to add to an app, but they do not scale as well as reactive forms. If you have very simple form with only static data, use template-driven forms. + +## A common foundation + +Both reactive and template-driven forms share underlying building blocks, the `FormControl`, `FormGroup` and the `ControlValueAccessor` interface. A `FormControl` instance tracks the value and validation status of an individual form control element. A `FormGroup` instance tracks the same values and statuses for a collection of form controls. How these control instances are created and managed with reactive and template-driven forms will be discussed later in this guide. + +## Control value accessors + +Control value accessors define a bridge between Angular forms and native DOM elements. The `ControlValueAccessor` interface defines methods for interacting with native elements including: reading from and writing values to them, providing callback functions to listen for value changes, when they are touched, and or enabled or disabled. A [default control value accessor](api/forms/DefaultValueAccessor) is attached to every input element when using either forms modules in Angular. + +## Forms data flows + +When building forms in Angular, its important to be able understand how the the framework handles data flows from user input to the form and changes from code. Reactive and template-driven follow two different strategies when handling these scenarios. Using a simple component with a single input field, we can illustrate how changes are handled. + +Here is a component with an input field for a single control using reactive forms. + +```typescript +@Component({ + template: `Name: ` +}) +export class ReactiveNameComponent { + name = new FormControl(); +} +``` + +Let’s look at how the data flows for an input with reactive forms. + +**Diagram of Input Event flow For Reactive Forms** + +When text is entered into the input field, the control is immediately updated to the new value, which then emits a new value through an observable. The source of truth, the form model, is explicitly defined with the form control in the component class. This model is created independently of the UI and is used to provide the value and validation status for the control instance. Reactive forms use directives to link existing form control instances to form elements in the view. This is important because you have full control over the form model without ever rendering the UI. The source of truth is always correct, because it is synchronously updated at the time changes are made. + +Now let’s look at the same data flows with template-driven forms. + +```typescript +@Component({ + template: `Name: ` +}) +export class TemplateNameComponent { + name = ‘’; +} +``` + +**Diagram of Input Event flow For Reactive Forms** + +Template-driven forms are less explicit in that the source of truth for is the directives in the template. Directives are necessary to bind the model to the component class. You no longer have direct control of the form model. Template-driven forms use directives such as NgModel and NgModelGroup to create the form control or group instances and manage their lifecycle within the change detection cycle. This abstraction promotes simplicity over structure. Because template-driven forms are dependent on the UI, the change detection process must complete its cycle where it checks for values changes, queues a task for the value to be updated, and performs a tick before the source of truth is correct. The process happens asynchronously to prevent errors from occuring with values changing during the change detection cycle and introduces unpredictability for querying the source of truth. + +## Custom validation and testing + +Validation is an integral part of managing any set of forms. Whether you’re checking for required fields or querying an external API for an existing username, Angular provides a set of built-in validators as well as the ability to create custom validators. With reactive forms, creating custom validators are achieved functions that receives control to validate and returns a result immediately. Because template-driven forms are tied to directives, custom validator directives must be created to wrap a validator function in order to use it in a template. + +For more on form validation, visit the [Form Validation](guide/form-validation) guide. + +Testing also plays a large part in complex applications and an easier testing strategy is always welcomed. Reactive forms provide an easy testing strategy to due to synchronous access to the form and data models, where controls and data can be queried and manipulated easily through the control without rendering a view. Template-driven forms are asynchronous, which complicates complex testing scenarios. It involves more detailed knowledge of the change detection process and how directives run on each cycle to ensure elements can be queried at the correct time. In order to access the underlying controls with template-driven forms, you must use `ViewChild` to access the `NgForm` and wait for the appropiate lifecycle hooks to finish before extracting any values, testing its validity or changing its value. + +## Scalability + +If forms are a central part of your application, scalability is very important. Being able to reuse form models across components and data access is critical. Reactive forms makes creating large scale forms easier by providing access to low-level APIs and synchronous access to the data model. Because template-driven forms focus on simplicity and simple scenarios with static content and little validation, they are not as reusable and abstract away the low-level APIs and access to the data model is handled asynchronously. + +## Key differences + +The table below summarizes the key differences in reactive and template driven forms. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + Reactive + + Template-Driven +
+ Setup + + More Explicit + + Less Explicit +
+ Source of truth + + The form model + + The directives in the template +
+ Form Model creation + + Class + + Form Directives +
+ Predictability + + Synchronous + + Asynchronous +
+ Consistency + + Immutable + + Mutable +
+ Data model + + Structured + + Unstructured +
+ Custom Validators + + Functions + + Directives +
+ Scalability + + Low-level API access + + Abstraction on top of APIs +
+ +## Next Steps + +After you understand the two approaches to handling form inputs, you can learn more about common examples and practices using reactive forms or template-driven forms. The following guides are the next steps in the learning process for each approach. + + +* [Reactive Forms](guide/reactive-forms) +* [Form Validation](guide/form-validation#reactive-form-validation) +* [Dynamic forms](guide/dynamic-form) + + +* [Template-driven Forms](guide/forms) +* [Form Validation](guide/form-validation#template-driven-validation) diff --git a/aio/content/guide/reactive-forms.md b/aio/content/guide/reactive-forms.md index 32eeb5bdee..4a6ed6e74e 100644 --- a/aio/content/guide/reactive-forms.md +++ b/aio/content/guide/reactive-forms.md @@ -16,7 +16,7 @@ Reactive forms use an explicit and immutable approach to managing the state of a Reactive forms also provide a straightforward path to testing because you are assured that your data is consistent and predictable when requested. Any consumers of the streams have access to manipulate that data safely. -Reactive forms differ from template-driven forms in distinct ways. Reactive forms provide more predictability with synchronous access to the data model, immutability with observable operators, and change tracking through observable streams. If you prefer direct access to modify data in your template, template-driven forms are less explicit because they rely on directives embedded in the template, along with mutable data to track changes asynchronously. See the [Appendix](#appendix) for detailed comparisons between the two paradigms. +Reactive forms differ from template-driven forms in distinct ways. Reactive forms provide more predictability with synchronous access to the data model, immutability with observable operators, and change tracking through observable streams. If you prefer direct access to modify data in your template, template-driven forms are less explicit because they rely on directives embedded in the template, along with mutable data to track changes asynchronously. See the [Forms Overview](guide/forms-overview) for detailed comparisons between the two paradigms. ## Getting started @@ -645,48 +645,3 @@ Listed below are the base classes and services used to create and manage form co - -### Comparison to template-driven forms - -*Template-driven* forms, introduced in the [Template-driven forms guide](guide/forms), take a completely different approach compared to reactive forms. With template-drive forms, you follow these rules: - -* Place HTML form controls (such as `` and `