3

我想检查我的表单中是否至少有一个字段被更改。如果这种情况为真,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;
   }
}

问题是,该按钮仅在更改所有字段时才禁用。我应该在条件或 for 循环中添加什么?

4

4 回答 4

5

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

this.disableButton = form.dirty;

如果您想排除“回溯” - 添加然后删除某些内容,您可以使用markAsPristine()方法将控件设置pristine为何时更改的值与最初的值相同。您可以拥有初始值的对象:

const initialValues = {prop: 3};
form.valueChanges.subscribe((changes)=>{
    for (prop in changes) {
       if (changes[prop] === initialValues[prop]) {
           form.get(prop).markAsPristine();
       }
    }
});
于 2017-07-25T06:49:32.533 回答
3

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

于 2017-07-25T06:49:59.787 回答
1

当你发现一个值被改变时,只需添加一个中断。

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

   }
}
于 2017-07-25T06:53:17.390 回答
0
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>
于 2020-11-23T18:44:58.620 回答