Angular 7 Forms
Angular forms are used to handle user's input. We can use Angular form in our application to enable users to log in, to update profile, to enter information, and to perform many other data-entry tasks.
In Angular 7, there are 2 approaches to handle user's input through forms:
Both approaches are used to collect 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.
Reactive Forms vs. Template-driven Forms
Both Reactive forms and Template-driven forms manage and process data differently. Each offers different advantages.
Difference between Reactive Forms and Template-driven Forms
Similarity between Reactive Forms and Template-driven Forms
There are some building blocks which are shared by both reactive and template-driven forms:
Form Model Setup
Form model setup is used to track value changes between Angular forms and form input elements. Let's take an example to see how the form model is defined and created.
Form model setup in Reactive forms
See the below component with an input field for a single control implemented using reactive forms.
In reactive forms, the form model is the source of truth. The source of truth provides the value and status of the form element at a given point in time.
Here, in the example above, the form model is the FormControl instance.
In reactive forms, the form model is explicitly defined in component class. After that the reactive form directive (here, it is: FormControlDirective) links the existing FormControl instance to a specific form element in the view using a value accessor (ControlValueAccessor instance).
Form model setup in Template-driven Forms
See the same above component with an input field for a single control implemented using template-driven forms.
In template-driven forms, the source of truth is template itself.
The form model abstraction promotes simplicity over structure. The template-driven form directive NgModel creates and manages the FormControl instance for a given form element. It's less explicit, but it removes the direct control over the form model.