Forms 角度2:比较两种形式
我想比较表单的两个值是否相同。我有这个Forms 角度2:比较两种形式,forms,angular,angular-reactive-forms,reactive-forms,formgroups,Forms,Angular,Angular Reactive Forms,Reactive Forms,Formgroups,我想比较表单的两个值是否相同。我有这个 if(this.holdForm.value != this.positionForm.value){ this.enableButton = true; }else{ this.enableButton = false; } 但它不起作用。它不会使enableButton成为真 更新: 无法直接比较对象值: var person1 = {name:"John"}; var person2 = {name:"John"}; console
if(this.holdForm.value != this.positionForm.value){
this.enableButton = true;
}else{
this.enableButton = false;
}
但它不起作用。它不会使enableButton成为真
更新:
无法直接比较对象值:
var person1 = {name:"John"};
var person2 = {name:"John"};
console.log(person1===person2) // will give you false
这是因为person1
和person2
都指向内存中的两个不同引用
如果您只想比较两个对象的值,可以使用一种简单但昂贵的方法:将它们字符串化,然后比较字符串:
JSON.stringify(person1) === JSON.stringify(person2) //this gives you true
使用上面的字符串化方法有很多限制。其中之一是对象物质中属性的顺序。您可能需要考虑一种更通用的解决方案来比较对象。您不能直接比较对象值:
var person1 = {name:"John"};
var person2 = {name:"John"};
console.log(person1===person2) // will give you false
这是因为person1
和person2
都指向内存中的两个不同引用
如果您只想比较两个对象的值,可以使用一种简单但昂贵的方法:将它们字符串化,然后比较字符串:
JSON.stringify(person1) === JSON.stringify(person2) //this gives you true
使用上面的字符串化方法有很多限制。其中之一是对象物质中属性的顺序。您可能需要考虑一种更通用的解决方案来比较对象。您应该做的是编写一个自定义验证器,例如检查密码是否与确认密码字段匹配的验证器。比如:
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}
}
}
然后,您可以根据验证状态启用/禁用按钮。IMHO是最干净的解决方案。您应该做的是编写一个自定义验证器,例如检查密码是否与确认密码字段匹配的验证器。比如:
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}
}
}
然后,您可以根据验证状态启用/禁用按钮。我知道什么是最干净的解决方案。你有什么错误?你能把这两张表贴出来吗?我没有错。另一个是先前值的临时形式。我想比较一下是否有变化。请参见更新的@RahulsingYou可以使用类似库的lodash及其等效方法来比较两个对象!\u。isEqual(this.holdForm.value,this.positionForm.value)这基本上是一个JS问题,所以这里也有一些想法,我会用lodash tho:)你得到了什么错误?你能把这两张表贴出来吗?我没有错。另一个是先前值的临时形式。我想比较一下是否有变化。请参见更新的@RahulsingYou可以使用类似库的lodash及其等效方法来比较两个对象!\u。isEqual(this.holdForm.value,this.positionForm.value)这基本上是一个JS问题,所以这里也有一些想法,我会使用lodash tho:)