Reactive forms helps us manage the state of a form at a given point in time. It helps us to write some executable code when any value or state changes. It helps us to write complex validation rules in code. It has direct access to the data model of our form. The logic which we implement in model driven forms can be tested. And thus unit test can be done. Reactive forms are used to implement more advance forms. Template driven forms are mainly for simpler implementations.
ng new feedback-form
create a component: ng g c feedback-form
app.module.ts file import ReactiveFormsModule import { ReactiveFormsModule } from '@angular/forms';
feedback-form.component.ts import { FormGroup } from '@angular/forms'; Form group represents the entire form that we are going to build.
FormBuilder is used to build the form. import { FormGroup } from '@angular/forms';
styles.css, feedback-form.component and app.component
FormGroup represents the entire form. And the individual form elements will be represented by FormControl. Thus, FormControl is the building block of a FormGroup. import { FormGroup, FormBuilder, FormControl } from '@angular/forms';
Creating form groups inside form groups for holding similar form control elements e.g a group of checkboxes
Radio buttons is just a single input. Thus we are not having a different form group for this. While checkbox has multiple inputs with multiple values, so having a form group to wrap them around.
A Form Array is also like Form Group and can be used to create multiple form control elements. This is unique in the way that we can create/add/delete form control elements inside it.
In HTML we use "value" attribute. Thus giving the same data from value of an input into form control will set it as default selection.
Any form group or form control or form array can be cleared with reset()
json pipe used to view HTML data for easier coding
(ngSubmit)
WIRING FORMGROUP FROM TS INTO HTML
It links formcontrol created in ts with input file in html. This also takes care of two way binding of input.
Adding/removing more feedbacks
We can use [ngValue] from [ngSelect] to save object in a select also instead of just a string. Thus makes coding easier.
Note that better to replace name with formControlName or. Name and formControlName should be same.
Use get handler to get any formcontrol value in HTML template
ng-untouched - if input has not been touched even once ng-touched - if input is once touched or focused ng-pristine - if input's value has not been changed even once ng-dirty - if input's value has changed atleast once
valueChanges.subscribe and .get() handler
Validators.required, Validators.minLength to get errors data: use the errors property from the formscontrol object
Show error message if customer has a Washing Machine product and tries to choose Proper Installation option
ng build change base href="/projects/ui/customer-feedback-form/"