我是Angular的新手,正在尝试理解基本的表单验证代码。在这里,下面的checkValidEmail试图检查用户输入的电子邮件是否等于[email protected]。我不明白的是,当电子邮件为[email protected]时,为什么表单验证为假?有关完整的源代码-https://stackblitz.com/edit/angular-p4bz6e?file=src%2Fapp%2Fapp.component.ts
checkValidEmail(control: AbstractControl) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (control.value === '[email protected]') {
resolve({ test: false })
} else {resolve(null)}
}, 2000)
})
表单验证将失败,因为在抽象控件或用户定义的验证checkValidEmail
中,您将返回{ emailIsTaken: true }
。因此自定义验证返回的任何响应都将添加emailcontrol错误属性。
尝试在视图中打印它,由于添加的错误,因此表单无效。
<p> Form emailIsTaken {{form.controls.email.errors | json}}</p>