Dirty vs touched — Basic interview question for angular forms ?
Difference between dirty and touched
Let us understand the basic meaning
Touched — When control is touched, may user input anything or not input, both case considered as touched
Dirty- When form is touched with inputting some value then we call it dirty
in Angular for data flows from user input keyboard to server database in this journey first thing is keyboard or mouse/touchpad/etc user interaction to controls.
Here is project you can create a project with single input to experience the same. put control name as framework
or
Open the Default angular project in official Document
run this with stackblitz then in browser see the control and class on input for different scenario
Firstly Getting element by document in console
let element = document.getElementById(‘framework’);
…………………………………………………………….
Scenario 1 : No user interaction
Dirty and touched both false
element.__ngContext__.directives[1].isTouched
false
element.__ngContext__.directives[1].isDirty
false
Styling: class will be
class="ng-untouched ng-pristine ng-valid"
…………………………………………………………….
Scenario 2 : user interaction — user touched but not entered
Dirty will false and touched will be true
element.__ngContext__.directives[1].isTouched
true
element.__ngContext__.directives[1].isDirty
false
Styling: class will be
class="ng-pristine ng-valid ng-touched"
…………………………………………………………….
Scenario 3: user interaction — user touched and entered
Dirty will false and touched will be true
element.__ngContext__.directives[1].isTouched
true
element.__ngContext__.directives[1].isDirty
true
Styling: class will be
class="ng-valid ng-touched ng-dirty"
…………………………………………………………….