Types of Form
- In angular we have to classes to keep track of the state of input field and their validity
FormControl
- For each input field in the form we need to create an instance of
FormControl
- With the control class we can check
- value
- touched, untouched (input field is touched or not)
- dirty (value is changed), pristine (value not changed)
- valid, invalid
- errors
FormControl
tracks the value and validation status of an individual form control.
FormGroup
- Represents a group of controls in the form
- Each form is a control group it at least contains 1 control.
- In complex app you might form with multiple control group. 1 for Billing Address and 1 for Shipping Address
- Exposes property
- value
- touched, untouched
- dirty, pristine(clean)
- valid, invalid
- errors
- Formgroup valid property returns true if all the controls in the group are valid
- FormGroup tracks the values and status for a collection of form controls.
- To add validation to the form we need to create formgroup object for the form, formcontrol object for each input field in the form
- This way we can keep track of state of each input field in the form and entire form
Creating Controls
- Two way to create these control objects
- Create formcontrol for each control
- Create formgroup for each form
Option 1
- Applying directives in the template, Angular will create control objects implicitly under the hood
- Form built this way - template driven forms - build them using the template
Option 2
- Explicitly creating control objects - write code to create new instances of control group and control objects
- Form built this way - Reactive forms
Reactive Forms
- More control over validation logic
- Good for complex forms
- Unit testable the validation logic of the form
Template-driven
- Good for simple forms
- Simple validation
- Easier to create
- Less code