Char
Char

Reputation: 2133

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?

Upvotes: 3

Views: 9028

Answers (4)

Rajesh Kumar Kanumetta
Rajesh Kumar Kanumetta

Reputation: 322

editForm: FormGroup;
    this.editForm = this.fb.group({
      editCountry: ['', Validators.required],
      editDate: ['', Validators.required],
      editHolidayName: ['', Validators.required],
    });
     <div>
    <button [disabled]="!editForm.dirty" type="button" class="btn btn-primary miracle-submit m-t-5">Save</button>
    </div>

Upvotes: 0

Younis Ar M
Younis Ar M

Reputation: 941

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 = true;

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

   }
}

Upvotes: 1

Max Koretskyi
Max Koretskyi

Reputation: 105439

Angular tracks form controls values and sets the status to dirty if any of them has changed. You don't need to manually check each control. Just use .dirty property of the form:

this.disableButton = form.dirty;

If you want to exclude "backtracking" - adding and then removing something, you can use markAsPristine() method to set control to pristine state when the value that changed is the same as it was initially. You can have the object of initial values:

const initialValues = {prop: 3};
form.valueChanges.subscribe((changes)=>{
    for (prop in changes) {
       if (changes[prop] === initialValues[prop]) {
           form.get(prop).markAsPristine();
       }
    }
});

Upvotes: 5

Robby Cornelissen
Robby Cornelissen

Reputation: 97120

The pristine property (or the inverse dirty property) is what you're after. It's defined on the AbstractControl class, and indicates whether any changes have been made to your FormControl, FormGroup or FormArray.

Upvotes: 3

Related Questions