我有一个带有异步验证的HTML反应表单。验证失败后,我尝试使用[class.has-errors]="hasErrors"
将CSS类has-errors添加到其中,但它不起作用。
<form [formGroup]="myForm">
<input type="text" formControlName="name">
<input type="email" formControlName="email" [class.has-errors]="hasErrors">
<div *ngIf="myForm.get('email').status === 'PENDING'">
Checking...
</div>
<div *ngIf="myForm.get('email').status === 'VALID'">
Email is available!
</div>
<div *ngIf="myForm.get('email').errors && myForm.get('email').errors.emailTaken">
Oh noes, this email is already taken!
</div>
</form>
我有一个异步功能
validateEmailNotTaken(control: AbstractControl) {
return this.signupService.checkEmailNotTaken(control.value).map(res => {
console.dir(res);
this.hasErrors = !res;
console.log('this.hasErrors=', this.hasErrors);
return res ? null : { emailTaken: true };
});
}
我宣布我的formbuilder并以这种方式形成
ngOnInit() {
this.myForm = this.fb.group({
name: ['', Validators.required],
email: [
'',
[Validators.required, Validators.email],
this.validateEmailNotTaken.bind(this)
]
});
}
当我的异步失败时,如何在输入框中添加一个类?
答案 0 :(得分:-1)
按如下方式捕捉错误
validateEmailNotTaken(control: AbstractControl) {
return this.signupService.checkEmailNotTaken(control.value).map(res => {
console.dir(res);
this.hasErrors = !res;
console.log('this.hasErrors=', this.hasErrors);
return res ? null : { emailTaken: true };
}).catch(error => {
return Observable.throw(null);
});
}
在异步电子邮件验证失败时添加“has-errors”类
<input type="email" formControlName="email" [class.has-errors]="myForm.get('email').errors && myForm.get('email').errors.emailTaken">
在任何验证失败时添加'has-errors'类,
<input type="email" formControlName="email" [class.has-errors]="myForm.get('email').errors">