Angular 2:如果表单发生变化,则禁用按钮

Cha*_*har 3 forms field typescript angular angular-forms

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

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

Max*_*kyi 5

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

this.disableButton = form.dirty;
Run Code Online (Sandbox Code Playgroud)

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

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