parent
04dfca41f4
commit
e08955b557
|
@ -2,24 +2,26 @@
|
|||
|
||||
Handling user input with forms is the cornerstone of many common applications. You use forms to log in, to update a profile, to enter sensitive information, and to perform 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.
|
||||
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.
|
||||
* **Reactive forms** are more robust: they are more scalable, reusable, and testable. If forms are a key part of your application, or you're already using reactive patterns for building 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 basic form requirements and logic that can be managed solely in the template, 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.
|
||||
Both reactive and template-driven forms share underlying building blocks, the `FormControl`, `FormGroup` and `FormArray`. 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, and a `FormArray` instance tracks the same values and statues for an array 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.
|
||||
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, disabling or enabling their elements, and providing callback functions for when the control's value changes in the UI or becomes touched. A built-in accessor is attached to every form field when using either forms modules in Angular, unless a custom value accessor has been activated on that field.
|
||||
|
||||
## Forms data flows
|
||||
## Data flow in forms
|
||||
|
||||
When building forms in Angular, it's 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.
|
||||
When building forms in Angular, it's important to understand how the the framework handles data flowing from the user or from programmatic changes. 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.
|
||||
|
||||
### Data flow in reactive forms
|
||||
|
||||
Here is a component with an input field for a single control using reactive forms.
|
||||
|
||||
|
@ -36,7 +38,13 @@ 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.
|
||||
### Data flow in template-driven forms
|
||||
|
||||
In reactive forms, the source of truth is the form model (in this case, the `FormControl` instance), which is explicitly defined in the component class. This model is created independently of the UI and can be used to provide an initial value for the control. The reactive form directive (in this case, `FormControlDirective`) then links the existing form control instance to a specific form element in the view using a value accessor.
|
||||
|
||||
When text is entered into the input field, the field's value accessor immediately relays the new value to the FormControl instance, which then emits the value through the valueChanges observable.
|
||||
|
||||
With reactive forms, you have full control over the form model without ever rendering the UI. The source of truth is always up-to-date, because it is synchronously updated at the time changes are made.
|
||||
|
||||
Now let’s look at the same data flows with template-driven forms.
|
||||
|
||||
|
@ -51,15 +59,21 @@ export class TemplateNameComponent {
|
|||
|
||||
**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.
|
||||
In template-driven forms, the source of truth is the template, so developers create their desired form through the placement of template-driven directives such as `NgModel` and `NgModelGroup`. The directives then create the `FormControl` or `FormGroup` instances that make up the form model, link them with form elements through a value accessor, and manage them within the constraints of the template's change detection cycle.
|
||||
|
||||
This abstraction promotes simplicity over structure. It is less explicit, but you no longer have direct control over the form model. It is simple to add directives, but because these directives are dependent on the UI, they must work around the change detection cycle. Programmatic value changes are registered during change detection (as they occur through an `Input` to a directive), so it's not possible to update the value and validity immediately because it may affect elements that have already been checked in that view, for example, the parent form. For this reason, value changes are delayed until the next tick, which allows change detection to complete and a new change detection process to be triggered with the updated value. In other words, the process happens asynchronously 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.
|
||||
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, custom validators are functions that receive a control to validate. 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.
|
||||
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, you must wait for the appropiate lifecycle hooks to finish before extracting any values, testing its validity or changing its value.
|
||||
|
||||
## Mutability
|
||||
|
||||
How changes are tracked plays a role in the efficiency of your application. Reactive forms keep the data model pure by providing it as an immutable data structure. Each time the a change is triggered on the data model, a new data model is returned rather than updating the data model directly. This is more efficient, giving you the ability track unique changes to the data model. It also follows reactive patterns that integrate with observable operators to map and transform data. Template-driven forms rely on mutability with two-way data binding to update the data model in the component as changes are made in the template.
|
||||
|
||||
## Scalability
|
||||
|
||||
|
|
Loading…
Reference in New Issue