我有以下代码。...
this.authForm = new FormGroup({
email: new FormControl("", [AuthValidator.required, Validators.email]),
password: new FormControl("", [
AuthValidator.required,
AuthValidator.minLength(5)
])
});
现在我想重置此表单,但是当我调用this.authForm.reset()时,它将引发错误,无法读取null的属性修剪。...
我有以下验证器。
export class AuthValidator {
static required(c: AbstractControl): ValidationErrors | null {
return (c.value as string).trim() ? null : { required: true };
}
static minLength(len: number): ValidatorFn {
return (c: AbstractControl) => (c.value as string).trim().length < len ? { minlength: { requiredLength: len, actualLength: c.value.length } } : null;
}
}
如何重置我的表格?请帮助
我尝试了所有的技巧。
this.authForm.markAsPristine等。但是失败了。...
答案 0 :(得分:1)
您正在将控制值转换为自定义验证器中的字符串。但是,可以在表单重置后为null
或undefined
。修改您的验证程序,以在使用trim()
之前检查有效的字符串。
export class AuthValidator {
static required(c: AbstractControl): ValidationErrors | null {
return (c.value && (c.value as string).trim()) ? null : { required: true };
}
static minLength(len: number): ValidatorFn {
return (c: AbstractControl) => (c.value && (c.value as string).trim().length < len) ? { minlength: { requiredLength: len, actualLength: c.value.length } } : null;
}
}