It is possible for an element within an Angular form to enter into the dirty
state without yet being touched
? I have some code in my template that, depending on the answer to this question, may be redundant.
<input class="form-control" #fName="ngModel" required />
<div *ngIf="fName.invalid && (fName.dirty || fName.touched)" class="form-error">
First name is required
</div>
This *ngIf
in this div
, for instance, could be simplified to fName.invalid && fName.touched
if there's no such thing as a dirty, untouched form control.
The difference between touched and dirty is that with touched the user doesn't need to actually change the value of the input control. touched is true of the field has been touched by the user, otherwise it's false. The opposite of touched is the property untouched .
According to the API docs (https://angular.io/api/forms/FormControl), the FormControl class extends AbstractControl , which has the dirty flag field/property. You can check a control's state like so: const nameControl = this. myForm.
What is dirty and pristine? pristine: This property returns true if the element's contents have not been changed. dirty: This property returns true if the element's contents have been changed. untouched: This property returns true if the user has not visited the element.
When the user changes the value in the watched field, the control is marked as "dirty" When the user blurs the form control element, the control is marked as "touched"
Yes.
By default Angular checks the dirty state on changes. So as the user types, the value is changed and the dirty state is set to true.
The touched state is not changed until the user leaves the field. It's like an "on lost focus" event. So as the user types, the dirty state is true but the touched state will be false. When the user leaves the field, both the dirty state and touched state will be true.
So if you want an error message to appear/disappear as the user is typing OR if the user just tabs/moves through the field, you will want to check both.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With