i try to bind value into ValidationErrors.
i have this method:
isUniqueEmail(control: FormControl): ValidationErrors {
if (control.value != null) {
console.log(control.value)
if(control.value == this.foundEmail){
console.log("found one");
return {isUniqueEmail: true}
}else{
return null;
}
}
}
this method check if control.value (email typing) equal email stored in global variable this.foundEmail
then we have duplicate email.
My problem is: i can retreive data from foundEmail in this method because this method is private.
this method is located inside export class exampleComponent
implements OnInit.
Error: ERROR TypeError: Cannot read properties of undefined (reading 'foundEmail')
But i check i have data into foundEmail
CodePudding user response:
The validator function gets called from the FormControl
so its context is not bound to the class you're defining the method on. You need to manually bind isUniqueEmail()
to this
.
Two options:
Use bind() when defining the FormControl:
name: new FormControl("", [ this.isUniqueEmail.bind(this), ]),
Define your validator as arrow function:
isUniqueEmail = (control: FormControl) => {
if (control.value != null) {
console.log(control.value)
if(control.value == this.foundEmail){
console.log("found one");
return {isUniqueEmail: true}
}else{
return null;
}
}
}