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:
- FormGroupDirective – Binds an existing FormGroup to a DOM element.
- Usage: [formGroup]=”farmersForm”
- FormGroupName – Syncs a nested FormGroup to a DOM element.
- Usage: formGroupName=”farmerAddress”
- FormControlDirective – Syncs a standalone FormControl instance to a form control element.
- Usage: [formControl]=”farmerName”
- FormControlName – Syncs a FormControl in an existing FormGroup to a form control element by name.
- Usage: formControlName=”farmerName”
(alternatively) [formControl]=ā€¯farmersForm.controls.farmerNameā€¯
- Usage: formControlName=”farmerName”
- FormArrayName – Syncs a nested FormArray to a DOM element.
- Usage: formArrayName=”grainsTypes”
Simply:
Example: Live Example