0

I'm working on an Angular app and I'm trying to figure out how to check whether some specific fields in a form have been changed. Users within this page have an option to either enter a new record, or select an option from a grid which will then populate the form. If they have already started entering information as a new record, and then decide to make a selection from the grid, I want to check to see if the user has already started filling out the form and, if they have made changes in one of the specific fields, throw a confirmation dialog before the code proceeds.

Here's my code:

checkNewEntry(): boolean {
  let fieldsChanged = false;

  if (this.form.get('field1').dirty) {
    fieldsChanged = true;
  } else if (this.form.get('field2').dirty) {
    fieldsChanged = true;
  } else if (this.form.get('field3').dirty) {
    fieldsChanged = true;
  } 

  return fieldsChanged;
}

Only there's a lot more than just three fields and I'm sure there's a more elegant way to approach this than a huge if-else but I'm still pretty new to Angular. I'm thinking about putting a class on the fields, selecting those fields, and then just looping through and checking them but I'm having a hard time finding direction for that.

TrevorGoodchild
  • 978
  • 2
  • 23
  • 49

1 Answers1

1

You can check the whole form change if you want (dirty or pristine). Any change on the form will trigger the action. See this answer:

How to check for changes in form in Angular 2 using

And if you want some specific ones then you can maintain a boolean and change its state on change of those specific form controls. And check the boolean's status before proceeding.

let fieldsChanged = false; 
<input foromControlName ="field1" (change)="setChecker()"></input> 
<input foromControlName ="field2" (change)="setChecker()"></input> 
<input foromControlName ="field3" (change)="setChecker()"></input> 

setChecker() { this.fieldsChanged = true } 

if(this.fieldsChanged) { show dialog }
Shofol
  • 693
  • 1
  • 11
  • 26