8

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.

Jacob Stamm
  • 1,660
  • 1
  • 29
  • 53

2 Answers2

19

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.

DeborahK
  • 57,520
  • 12
  • 104
  • 129
0
*ngIf="fName.invalid && fName.hasError('required')"

With this condition, the message is displayed when the form is submitted (and invalid) or when the field is touched.

Tim
  • 5,435
  • 7
  • 42
  • 62
H.JA
  • 1