2017-07-25 71 views
0

我想检查是否我的表格中至少有一个字段发生了变化。如果这种情况属实,disableButton将设置为truefalse如果有没有更改的形式。下面是我当前的代码:角度2:禁用按钮如果表格中有变化

// 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字段 改变了按钮只会关闭。我应该在我的状况或循环中添加什么?

回答

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

    } 
} 
+0

仍然无效@YounisArM – Char

+0

当值相同时,你将它设置为true,这与你想要的相反,我已经改变了代码,现在尝试 –

+0

你不需要改变布尔值。但是这工作。谢谢@YounisArM – Char

3

角度轨迹形成控制值并将状态设置为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(); 
     } 
    } 
}); 
+0

,但你是什么意思,如果用户删除的变化,它仍然是脏的右@Maximus – Char

+0

如果有值'了'然后将用户添加'B'所以它'ab'现在,然后取出'b'和'a'会保留原来的状态吗? –

+0

是的。这仍然是肮脏的权利? @Maximus – Char

3

pristine属性(或逆dirty属性)是你追求的。它在AbstractControl类中定义,并指出是否对您的FormControlFormGroupFormArray进行了任何更改。