{ "id": "guide/forms-overview", "title": "Introduction to forms in Angular", "contents": "\n\n\n
\n mode_edit\n
\n\n\n
\n

Introduction to forms in Angularlink

\n

Handling user input with forms is the cornerstone of many common applications. Applications use forms to enable users to log in, to update a profile, to enter sensitive information, and to perform many other data-entry tasks.

\n

Angular provides two different approaches to handling user input through forms: reactive and template-driven. Both capture user input events from the view, validate the user input, create a form model and data model to update, and provide a way to track changes.

\n

This guide provides information to help you decide which type of form works best for your situation. It introduces the common building blocks used by both approaches. It also summarizes the key differences between the two approaches, and demonstrates those differences in the context of setup, data flow, and testing.

\n

Prerequisiteslink

\n

This guide assumes that you have a basic understanding of the following.

\n\n

Choosing an approachlink

\n

Reactive forms and template-driven forms process and manage form data differently. Each approach offers different advantages.

\n\n

Key differenceslink

\n

The table below summarizes the key differences between reactive and template-driven forms.

\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
ReactiveTemplate-driven
Setup of form modelExplicit, created in component classImplicit, created by directives
Data modelStructured and immutableUnstructured and mutable
PredictabilitySynchronousAsynchronous
Form validationFunctionsDirectives
\n

Scalabilitylink

\n

If forms are a central part of your application, scalability is very important. Being able to reuse form models across components is critical.

\n

Reactive forms are more scalable than template-driven forms. They provide direct access to the underlying form API, and synchronous access to the form data model, making creating large-scale forms easier.\nReactive forms require less setup for testing, and testing does not require deep understanding of change detection to properly test form updates and validation.

\n

Template-driven forms focus on simple scenarios and are not as reusable.\nThey abstract away the underlying form API, and provide only asynchronous access to the form data model.\nThe abstraction of template-driven forms also affects testing.\nTests are deeply reliant on manual change detection execution to run properly, and require more setup.

\n\n

Setting up the form modellink

\n

Both reactive and template-driven forms track value changes between the form input elements that users interact with and the form data in your component model.\nThe two approaches share underlying building blocks, but differ in how you create and manage the common form-control instances.

\n

Common form foundation classeslink

\n

Both reactive and template-driven forms are built on the following base classes.

\n\n\n

Setup in reactive formslink

\n

With reactive forms, you define the form model directly in the component class.\nThe [formControl] directive links the explicitly created FormControl instance to a specific form element in the view, using an internal value accessor.

\n

The following component implements an input field for a single control, using reactive forms. In this example, the form model is the FormControl instance.

\n\nimport { Component } from '@angular/core';\nimport { FormControl } from '@angular/forms';\n\n@Component({\n selector: 'app-reactive-favorite-color',\n template: `\n Favorite Color: <input type=\"text\" [formControl]=\"favoriteColorControl\">\n `\n})\nexport class FavoriteColorComponent {\n favoriteColorControl = new FormControl('');\n}\n\n\n\n

Figure 1 shows how, in reactive forms, the form model is the source of truth; it provides the value and status of the form element at any given point in time, through the [formControl] directive on the input element.

\n

Figure 1. Direct access to forms model in a reactive form.

\n
\n \"Reactive\n
\n

Setup in template-driven formslink

\n

In template-driven forms, the form model is implicit, rather than explicit. The directive NgModel creates and manages a FormControl instance for a given form element.

\n

The following component implements the same input field for a single control, using template-driven forms.

\n\nimport { Component } from '@angular/core';\n\n@Component({\n selector: 'app-template-favorite-color',\n template: `\n Favorite Color: <input type=\"text\" [(ngModel)]=\"favoriteColor\">\n `\n})\nexport class FavoriteColorComponent {\n favoriteColor = '';\n}\n\n\n\n

In a template-driven form the source of truth is the template. You do not have direct programmatic access to the FormControl instance, as shown in Figure 2.

\n

Figure 2. Indirect access to forms model in a template-driven form.

\n
\n \"Template-driven\n
\n\n

Data flow in formslink

\n

When an application contains a form, Angular must keep the view in sync with the component model and the component model in sync with the view.\nAs users change values and make selections through the view, the new values must be reflected in the data model.\nSimilarly, when the program logic changes values in the data model, those values must be reflected in the view.

\n

Reactive and template-driven forms differ in how they handle data flowing from the user or from programmatic changes.\nThe following diagrams illustrate both kinds of data flow for each type of form, using the favorite-color input field defined above.

\n

Data flow in reactive formslink

\n

In reactive forms each form element in the view is directly linked to the form model (a FormControl instance). Updates from the view to the model and from the model to the view are synchronous and do not depend on how the UI is rendered.

\n

The view-to-model diagram shows how data flows when an input field's value is changed from the view through the following steps.

\n
    \n
  1. The user types a value into the input element, in this case the favorite color Blue.
  2. \n
  3. The form input element emits an \"input\" event with the latest value.
  4. \n
  5. The control value accessor listening for events on the form input element immediately relays the new value to the FormControl instance.
  6. \n
  7. The FormControl instance emits the new value through the valueChanges observable.
  8. \n
  9. Any subscribers to the valueChanges observable receive the new value.
  10. \n
\n
\n \"Reactive\n
\n

The model-to-view diagram shows how a programmatic change to the model is propagated to the view through the following steps.

\n
    \n
  1. The user calls the favoriteColorControl.setValue() method, which updates the FormControl value.
  2. \n
  3. The FormControl instance emits the new value through the valueChanges observable.
  4. \n
  5. Any subscribers to the valueChanges observable receive the new value.
  6. \n
  7. The control value accessor on the form input element updates the element with the new value.
  8. \n
\n
\n \"Reactive\n
\n

Data flow in template-driven formslink

\n

In template-driven forms, each form element is linked to a directive that manages the form model internally.

\n

The view-to-model diagram shows how data flows when an input field's value is changed from the view through the following steps.

\n
    \n
  1. The user types Blue into the input element.
  2. \n
  3. The input element emits an \"input\" event with the value Blue.
  4. \n
  5. The control value accessor attached to the input triggers the setValue() method on the FormControl instance.
  6. \n
  7. The FormControl instance emits the new value through the valueChanges observable.
  8. \n
  9. Any subscribers to the valueChanges observable receive the new value.
  10. \n
  11. The control value accessor also calls the NgModel.viewToModelUpdate() method which emits an ngModelChange event.
  12. \n
  13. Because the component template uses two-way data binding for the favoriteColor property, the favoriteColor property in the component\nis updated to the value emitted by the ngModelChange event (Blue).
  14. \n
\n
\n \"Template-driven\n
\n

The model-to-view diagram shows how data flows from model to view when the favoriteColor changes from Blue to Red, through the following steps

\n
    \n
  1. The favoriteColor value is updated in the component.
  2. \n
  3. Change detection begins.
  4. \n
  5. During change detection, the ngOnChanges lifecycle hook is called on the NgModel directive instance because the value of one of its inputs has changed.
  6. \n
  7. The ngOnChanges() method queues an async task to set the value for the internal FormControl instance.
  8. \n
  9. Change detection completes.
  10. \n
  11. On the next tick, the task to set the FormControl instance value is executed.
  12. \n
  13. The FormControl instance emits the latest value through the valueChanges observable.
  14. \n
  15. Any subscribers to the valueChanges observable receive the new value.
  16. \n
  17. The control value accessor updates the form input element in the view with the latest favoriteColor value.
  18. \n
\n
\n \"Template-driven\n
\n

Mutability of the data modellink

\n

The change-tracking method plays a role in the efficiency of your application.

\n\n

The difference is demonstrated in the previous examples that use the favorite-color input element.

\n\n\n

Form validationlink

\n

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.

\n\n

For more information, see Form Validation.

\n

Testinglink

\n

Testing plays a large part in complex applications. A simpler testing strategy is useful when validating that your forms function correctly.\nReactive forms and template-driven forms have different levels of reliance on rendering the UI to perform assertions based on form control and form field changes.\nThe following examples demonstrate the process of testing forms with reactive and template-driven forms.

\n

Testing reactive formslink

\n

Reactive forms provide a relatively easy testing strategy because they provide synchronous access to the form and data models, and they can be tested without rendering the UI.\nIn these tests, status and data are queried and manipulated through the control without interacting with the change detection cycle.

\n

The following tests use the favorite-color components from previous examples to verify the view-to-model and model-to-view data flows for a reactive form.

\n

Verifying view-to-model data flow

\n

The first example performs the following steps to verify the view-to-model data flow.

\n
    \n
  1. Query the view for the form input element, and create a custom \"input\" event for the test.
  2. \n
  3. Set the new value for the input to Red, and dispatch the \"input\" event on the form input element.
  4. \n
  5. Assert that the component's favoriteColorControl value matches the value from the input.
  6. \n
\n\nit('should update the value of the input field', () => {\n const input = fixture.nativeElement.querySelector('input');\n const event = createNewEvent('input');\n\n input.value = 'Red';\n input.dispatchEvent(event);\n\n expect(fixture.componentInstance.favoriteColorControl.value).toEqual('Red');\n});\n\n\n

The next example performs the following steps to verify the model-to-view data flow.

\n
    \n
  1. Use the favoriteColorControl, a FormControl instance, to set the new value.
  2. \n
  3. Query the view for the form input element.
  4. \n
  5. Assert that the new value set on the control matches the value in the input.
  6. \n
\n\nit('should update the value in the control', () => {\n component.favoriteColorControl.setValue('Blue');\n\n const input = fixture.nativeElement.querySelector('input');\n\n expect(input.value).toBe('Blue');\n});\n\n\n

Testing template-driven formslink

\n

Writing tests with template-driven forms requires a detailed knowledge of the change detection process and an understanding of how directives run on each cycle to ensure that elements are queried, tested, or changed at the correct time.

\n

The following tests use the favorite color components mentioned earlier to verify the data flows from view to model and model to view for a template-driven form.

\n

The following test verifies the data flow from view to model.

\n\nit('should update the favorite color in the component', fakeAsync(() => {\n const input = fixture.nativeElement.querySelector('input');\n const event = createNewEvent('input');\n\n input.value = 'Red';\n input.dispatchEvent(event);\n\n fixture.detectChanges();\n\n expect(component.favoriteColor).toEqual('Red');\n }));\n\n\n

Here are the steps performed in the view to model test.

\n
    \n
  1. Query the view for the form input element, and create a custom \"input\" event for the test.
  2. \n
  3. Set the new value for the input to Red, and dispatch the \"input\" event on the form input element.
  4. \n
  5. Run change detection through the test fixture.
  6. \n
  7. Assert that the component favoriteColor property value matches the value from the input.
  8. \n
\n

The following test verifies the data flow from model to view.

\n\nit('should update the favorite color on the input field', fakeAsync(() => {\n component.favoriteColor = 'Blue';\n\n fixture.detectChanges();\n\n tick();\n\n const input = fixture.nativeElement.querySelector('input');\n\n expect(input.value).toBe('Blue');\n }));\n\n\n

Here are the steps performed in the model to view test.

\n
    \n
  1. Use the component instance to set the value of the favoriteColor property.
  2. \n
  3. Run change detection through the test fixture.
  4. \n
  5. Use the tick() method to simulate the passage of time within the fakeAsync() task.
  6. \n
  7. Query the view for the form input element.
  8. \n
  9. Assert that the input value matches the value of the favoriteColor property in the component instance.
  10. \n
\n

Next stepslink

\n

To learn more about reactive forms, see the following guides:

\n\n

To learn more about template-driven forms, see the following guides:

\n\n\n \n
\n\n\n" }