If the user doesn’t change the value of a control. Then the control state is ‘pristine’
If the user change the value of a control, then the state will be changed to ‘dirty’ from ‘pristine’
Similarly, if all the controls in the form are in pristine state, then the form state is also ‘pristine’
If any of the control is in a dirty state, the form will be dirty.
Validity
Valid and error states are used to check the validity of the control of entire form.
If the value of the control match with all the rules or formats, then the control state would be ‘valid’. If any of the rules or format is violated, then the control state will give an error.
If all the controls are in a valid state, the form state also would be valid.
Visited
If the user performs any action, like clicking or selecting a control, its touched state will be true. Otherwise, it would be in an untouched state.
Angular CSS Classes
In Angular, the states are managed by some CSS classes. They are:
- ng-pristine ,ng-dirty
- ng-valid, ng-invalid
- ng-touched, ng-untouched
This classes will be dynamically added and removed from the form controls and forms based on the user interactions
Please refer to the screenshot below:
If we click the text box the ng-untouched will be removed and ng-touched will added.
Please refer to the screenshot below:
I have added the ‘required’ validation for this input box. Therefore, we should provide some value from this control. Only then, it becomes valid.
If we type any value inside this text box, the ‘ng-pristine’ class is removed and ‘ng-dirty’ class will be added.
The ng-invalid class will also be removed and ng-valid will be added.
Please refer the screenshot below:
We will learn more about form validation in the coming articles:
Form Building Blocks
Angular forms have 3 important building blocks to track the states and values of the forms and their controls
They are:
- FormControl
- FormGroup
- FormModel
FormControl will track the value and states of an individual input element such as a text box.
FormGroup is used to track the value and states of a group of the form control. Form itself is considered as a form group.
FormModel is used as a data structure that represents the HTML form.
It will retain the form states,form values, and child controls.
Angular will automatically create the FormModel
These building blocks are common for both template-driven and reactive forms.
Summary
This is an introductory article about Angular forms. We learned about the Angular form's basic information, two approaches, and their differences.
In the next article, we will learn more about template-driven forms and their implementation.