How to check an ngModel input field is dirty?

7.1k Views Asked by At

I have this HTML template:

<input type="text"
  ngModel
  #myValue="ngModel"
  name="{{ fieldName }}"
  id="{{ fieldName }}"
  value="{{ myVal }}"
  class="form-control"
  (change)="checkDirty(myValue)">

How do I check this field is dirty in my.component.ts file?

Now I have only this basic code in my.component.ts file:

export class UriFieldComponent implements OnInit {
    constructor() { }

    ngOnInit() { }

    checkDirty(value) {
        // in here I need to check is dirty or not
    }
}
1

There are 1 best solutions below

0
On BEST ANSWER

NgModel class has an dirty property in it. This mean you can do:

checkDirty(value) {
    if (value.dirty) {
      ...
    }
}

But, the way you use it is incorrect, if you check the dirty property on input change it is obvious that the input is dirty!. In other words, if you're getting to your checkDirty function the input is always dirty.