Разделить пользовательский валидатор на несколько функций Angular 2
export class FormFieldErrorExample {
email = new FormControl('', [Validators.required, Validators.email, this.lengthValidator]);
getErrorMessage() {
return this.email.hasError('required') ? 'You must enter a value' :
this.email.hasError('email') ? 'Not a valid email' :
'minimum length should be greater than 10';
}
lengthValidator(control : AbstractControl){
if(control.value.length <10)
return {lengthError : true};
else return this.anotherValidator(control);
}
anotherValidator(control: AbstractControl){
return {lengthError : true};
}
Я попытался разделить валидатор на другую функцию, но получаю сообщение об ошибке типа "Невозможно прочитать свойство"anotherValidator"undefined". Как я могу разделить валидатор на несколько функций и правильно передать управление
1 ответ
Решение
Вы должны передать контекст this
к вашему кастомалидатору lengthValidator
используя bind()
email = new FormControl('', [Validators.required, Validators.email, this.lengthValidator.bind(this)])