Angular 2: 如果表单有变化则禁用按钮

Angular 2: disable button if there are changes in form

我想检查 我的表单中是否至少有一个字段被更改。如果这种情况成立,disableButton 将设置为 true,如果 没有变化,则 false 在表格中。以下是我当前的代码:

// 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;
   }
}

问题是,只有当 ALL 字段是 变了。我应该在条件或 for 循环中添加什么?

Angular 跟踪表单控件值并将状态设置为 dirty(如果其中任何一个已更改)。您不需要手动检查每个控件。只需使用 .dirty 属性 形式:

this.disableButton = form.dirty;

如果你想排除"backtracking" - 添加然后删除一些东西,你可以使用markAsPristine()方法将控件设置为pristine状态,当更改的值与最初是。您可以拥有初始值的对象:

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

pristine 属性(或相反的 dirty 属性)就是您所追求的。它在 AbstractControl class 上定义,并指示是否对您的 FormControlFormGroupFormArray.

进行了任何更改

当你发现一个值被改变的时候加一个break就可以了。

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;
        }

   }
}
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>