Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can an element in Angular 2+ be dirty without being touched?

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.

like image 230
Jacob Stamm Avatar asked Jan 22 '18 19:01

Jacob Stamm


People also ask

What is the difference between dirty and touched?

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 .

How do you know if angular is dirty?

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's the difference between dirty touched and pristine on a form element?

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.

What is dirty property in angular?

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"


1 Answers

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.

like image 94
DeborahK Avatar answered Oct 14 '22 19:10

DeborahK