Reactive Forms – Angular v5.x

In the last article, we discussed Template-driven forms and this article is going to explore about Reactive forms. Both Reactive and template-driven form available under @angular/forms with module names of ReactiveFormsModule and FormsModule respectively.Reactive forms required more coding than template-driven way, but these will give more control on forms than template-driven.
Reactive Forms:
Instead of angular, we need to create FormGroup and FromControllers mapping between UI and form model.
Advantages:
1) Field Value and validity updates are always synchronous, so we won’t encounter the timing issues that sometimes occur in a template-driven form.
2) Reactive forms are easy to write Unit test cases because of most of the business logic available inside of the component.
REACTIVE DRIVEN DIRECTIVES:

  1. FormGroupDirective – Binds an existing FormGroup to a DOM element.
    • Usage: [formGroup]=”farmersForm”
  2. FormGroupName – Syncs a nested FormGroup to a DOM element.
    • Usage: formGroupName=”farmerAddress”
  3. FormControlDirective – Syncs a standalone FormControl instance to a form control element.
    • Usage: [formControl]=”farmerName”
  4. FormControlName – Syncs a FormControl in an existing FormGroup to a form control element by name.
    • Usage: formControlName=”farmerName”
      (alternatively) [formControl]=ā€¯farmersForm.controls.farmerNameā€¯
  5. FormArrayName – Syncs a nested FormArray to a DOM element.
    • Usage: formArrayName=”grainsTypes”

Simply:

Example: Live Example

Template Driven Forms API – Angular v5.x

Angular has rich form support regarding both template driven and reactive forms. This article is going to focus only on the template-driven forms and validations.
Template-Driven Forms :
Definition:
Angular will create FormGrop and FormControl objects based on applied directives like ngForm, ngModel, ngModelGroup and template reference variables from a form template.

TEMPLATE DRIVEN DIRECTIVES:

All above directives are available once we import FormsModule into application NgModule.
NgForm – Will create a top-level FormGroup instance and binds it to a form to track updates/validations.
NgModel – Will Creates a FormControl instance and will track input field value, events and validation rules.it will keep view and model in sync.
NgModelGroup – Will create a sub-group form controller to maintain nested structured model.
Simply:

Example: Live Example