Char Char - 3 years ago 89
TypeScript Question

Angular 2: disable button if there are changes in form

I want to check if at least one field in my form is changed. If this scenario is true, the

disableButton
will be set to true, and false if there are no changes in the form. Below is my current code:

// this.hold is an array that temporary holds the previous values of
// the form for comparison of the changes in form

if(this.data.process == 'update') {
for(const f in form.value){
if (form.value[f] == this.hold[f])
this.disableButton = true;
else
this.disableButton = false;
}
}


The problem is, the button only disables when ALL fields are
changed. What should I add in my condition or in for loop?

Answer Source

Just add a break when you find that a value is changed.

if(this.data.process == 'update') {
   for(const f in form.value){
       if (form.value[f] == this.hold[f]){
           this.disableButton = false;

       }    
       else{
          this.disableButton = true;
          break;
        }

   }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download