0

我想比較兩個表單的值是否相同。我有這個角2:比較2個表格

if(this.holdForm.value != this.positionForm.value){ 
    this.enableButton = true; 
}else{ 
    this.enableButton = false; 
} 

但它不起作用。它不會使enableButton爲真。

更新:

this.positionForm = this.fb.group({ 
      'name' : [position.name, Validators.required], 
      'remark': position.remark 
     }); 

    this.holdForm = this.fb.group({ 
     'name' : position.name, 
     'remark': position.remark 
    }); 



    this.positionForm.valueChanges.subscribe(data => { 
     this.onValueChanged(data); 
     if(this.data.process == 'register'){ 
      this.enableButton = true; 
     }else if(this.data.process == 'update' && this.holdForm.value != this.positionForm.value){ 
      this.enableButton = true; 
     }else{ 
      this.enableButton = false; 
     } 
    }); 
+1

你得到的錯誤是什麼?你可以發佈兩種形式 –

+0

我沒有錯誤。另一個是先前價值的臨時表格。我想比較是否有變化。看到更新的@RahulSingh – Char

+1

你可以使用像lodash庫和它的平等方法來比較兩個對象 !_ isEqual(this.holdForm.value,this.positionForm.value) –

回答

0

你應該做的是寫一個自定義的驗證器,例如一個檢查密碼是否與確認密碼字段匹配的驗證器。如:

this.formBuilder.group({ 
    password: [''], 
    confirmPassword: [''], 
    }, { 
    validator: matchingFieldsValidation("password", "confirmPassword") 
}) 

export function matchingFieldsValidation(firstControlName: string, secondControlName: string): ValidatorFn { 
    return (control: AbstractControl): {[key: string]: any} => { 
     const firstControl= control.get(firstControlName); 
     const secondControl= control.get(secondControlName); 
     if (!firstControl|| !secondControl) return null; 
     return firstControl.value == secondControl.value ? null : {matchingFields: true} 
    } 
} 

然後,您可以啓用/禁用按鈕取決於驗證狀態。恕我直言,最乾淨的解決方案。

0

不能在對象的值直接比較:

var person1 = {name:"John"}; 
var person2 = {name:"John"}; 
console.log(person1===person2) // will give you false 

這是因爲這兩個person1person2指向兩個不同參考記憶。

如果你只是想比較兩個對象的值,你可以有一個簡單,但昂貴的方式:字符串化它們,然後比較字符串:

JSON.stringify(person1) === JSON.stringify(person2) //this gives you true 

有使用字符串化的一個很大的侷限性方法。其中之一就是對象事物的屬性順序。您可能想要考慮更通用的解決方案來比較對象。

+0

我更新了我的問題@CozyAzure – Char