Angular form control states describe the state of a form control in Angular forms. These states allow tracking and responding to changes in the user input.
We can access these states through the form control instance in the component and use them to conditionally render UI elements, display error messages, and control the overall behavior of the form.
Some of the standard form control states are,
Form States |
True when? |
Pristine |
The user has not modified the form control |
Dirty |
The user has modified the form control |
Touched |
The user has interacted with the form control, e.g., by clicking or focusing on it. |
Untouched |
The form control has not been interacted with by the user. |
Valid |
The form control's value meets the validation rules defined in the application. |
Invalid |
The form control's value does not meet the validation rules defined in the application. |
These states are maintained and tracked internally using CSS classes.
Let's understand these states with an example,
We have a simple form with three input fields and a submit button. Only required validation enforced on Product Code.
Initially, when the form loads, the form states will be,
- ng-untouched because none of the form control has been clicked or focused out yet, and it's a default state
- ng-pristine because none of the form control has been modified yet, and it's a default state
- ng-invalid because some of the from control has required validation and which is not filled yet
When removing the cursor from the input field without entering any inputs, the form states modified to,
- ng-touched because form control has been clicked or focused out
- ng-pristine because none of the form control still not modified
- ng-invalid because some of the from control has required validation but are still not filled
When an input is provided in the required field, and the cursor has been removed from the input field, the form states change to,
- ng-touched because the element has already been visited
- ng-dirty because form control contents have been changed
- ng-valid because the required field has been filled now
NOTE: Overall form states have been derived from forms controls present in that form.
Ng-pristine vs. ng-dirty states is not interchangeable means if the form state change from pristine to dirty; then it will remain in a dirty state unless we do not load the form again. The same applies to ng-touched vs. ng-untouched. But ng-valid and ng-invalid states are interchangeable. The below image depicts the form states transition briefly:
In summary, pristine vs. dirty tells whether the user actually changed anything in the form, and touched vs. untouched tells whether the user has been visited there.
Happy Learning!