2017-07-25 36 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進行了任何更改。