角度2:比较2种形式

时间:2017-07-24 09:02:29

标签: forms angular angular-reactive-forms reactive-forms formgroups

我想比较表格的两个值是否相同。我有这个

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

2 个答案:

答案 0 :(得分:1)

您应该做的是编写自定义验证器,例如检查密码是否与确认密码字段匹配的验证器。像:

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

然后您可以根据验证状态启用/禁用按钮。恕我直言,最干净的解决方案。

答案 1 :(得分: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

使用上面的字符串化方法有很多限制。其中之一是对象中属性的顺序。您可能想要一个更通用的解决方案来比较对象。

相关问题