【发布时间】:2021-10-05 07:36:49
【问题描述】:
使用 Angular 12 我有一个带有客户端和服务器验证的简单示例表单。
-
我只想在第一次提交表单后显示客户端验证错误;
-
客户端验证成功后,我会显示服务器验证错误。
服务器验证错误在表单字段错误中添加为“不正确”字段。
-
我正在使用响应式表单。
表单按预期工作,但我不确定我的实现是否是最佳选择。
组件的 HTML
<form [formGroup]="form">
<label for="email">Email</label>
<input id="email" type="text" formControlName="email">
<span class="error" *ngIf="form.get('email')?.invalid && form.get('email')?.touched">
{{form.get('email')?.errors?.incorrect}}
<ng-container *ngIf="form.get('email')?.errors?.required">Email required</ng-container>
<ng-container *ngIf="form.get('email')?.errors?.email">Invalid email</ng-container>
</span>
<button type="submit" (click)="send()" [disabled]="submitted">Send</button>
</form>
组件的打字稿
export class Component implements OnInit {
form: FormGroup;
submitted: boolean;
constructor(private service: Service) {
this.form = this.formBuilder.group({
email: ['', [Validators.required, Validators.email]],
});
this.submitted = false;
}
send() {
this.submitted = true;
this.form.markAllAsTouched();
if (this.form.valid) {
this.service.send({email: this.form.value.email}).subscribe(
(next: Payload<Response>) => {
console.log("SUCCESS");
},
(error) => {
if (error.status === 400)
new FormGroupErrorBuilder(this.form).setErrors(error.errors);
this.submitted = false;
}
);
} else {
this.submitted = false;
}
}
}
FormGroupErrorBuilder
This is how I am adding server errors to Angular's FormGroup:
export class FormGroupErrorBuilder {
formGroup: FormGroup;
constructor(formGroup: FormGroup) {
this.formGroup = formGroup;
}
setErrors(errors: Error[]) {
for (let error of errors) {
var control = this.formGroup.get(error.name);
if (control)
control.setErrors({ incorrect: error.message });
}
}
}
问题
-
是否可以在首次提交时使用
this.form.markAllAsTouched();对所有表单字段进行验证? -
使用条件
*ngIf="form.get('email')?.invalid && form.get('email')?.touched"是显示表单字段错误的好选择吗?
欢迎任何改进代码的建议...
注意:
我正在使用submitted 变量来控制提交按钮是否被禁用并更改其 CSS 样式。
【问题讨论】:
标签: angular angular-reactive-forms angular2-forms