谁能解释一下下面的lambda函数?
此函数应将"mismatchedFields"设置为true/false,并将其作为对象返回,如果表单的field1
和field2
具有相同的值:
function matchingFields(field1, field2) {
return form => {
if(form.controls[field1].value !== form.controls[field2].value)
return { mismatchedFields: true }
}
}
它用于 Angular 表单验证器,如下所示:
export class NewUserComponent {
private form: any;
constructor(private fb: FormBuilder) {
this.form = fb.group({
password: '',
passwordConfirm: ''
}, { validator: matchingFields('password', 'passwordConfirm')})
}
}
我不明白'matchingFields'
在哪里向第一个'return'
返回的 lambda 函数提供变量'form'
谁能解释一下这个lambda函数的功能?
谢谢。
当你设置这个
validator: matchingFields('password', 'passwordConfirm')
你调用函数matchingFields
,它从中返回另一个函数(箭头/lambda 函数)。在此调用之后,您可以认为您有一个从matchingFields
返回的类似函数。
function someFunction(form) {
var field1 = 'password';
var field2 = 'passwordConfirm';
if(form.controls[field1].value !== form.controls[field2].value)
return { mismatchedFields: true }
}
在formGroup
现在你会有类似的东西
validator: someFunction
您刚刚将validator
的引用设置为函数someFunction
,这是从matchingFields
返回的引用。现在,Angular
将在验证阶段自动调用此函数,并且form
参数将自动传递给该函数。此form
是运行验证的。
FormBuilder
调用回调(即内部)。
matchingFields
定义只是它的通用版本:
…
constructor(private fb: FormBuilder) {
this.form = fb.group({
password: '',
passwordConfirm: ''
}, {
validator: form => {
if (form.controls['password'].value !== form.controls['passwordConfirm'].value) {
return { mismatchedFields: true }
}
}
})
}
所以我会想象在里面FormBuilder.group(a, b)
发生以下情况:
b.validator(this.internalFormReference)
下面是如何调用它的运行示例:
// The function from the question
function matchingFields(field1, field2) {
return form => {
if (form.controls[field1].value !== form.controls[field2].value)
return {
mismatchedFields: true
}
}
}
// A simplified version of the FormGroup object
const form = {
controls: {
a: {
value: 'test'
},
b: {
value: 'test2'
}
}
};
// as form.a.value !== form.b.value the validator should not be undefined
console.log(matchingFields('a', 'b')(form));