我的Angular Reactive Form运行良好,除非我填写了所有必填字段,然后按下Chrome的后退按钮(无论是否提交(,然后再次返回表单页面。我的表格仍在填写中,但我不能再提交表格了。我想是因为表单验证无效,我必须重新填写每个字段才能再次按下提交按钮。
如何强制重新验证表单,这样我就不必再次擦除和键入所有内容?
profileForm = this.fb.group({
checkbox: [false],
checkbox_cgv: [false, Validators.requiredTrue],
firstName: ['', Validators.required],
lastName: ['', Validators.required],
email:['', [Validators.required, Validators.email]],
phoneNumber:['', Validators.required],
billing: this.fb.group({
address1: ['', Validators.required],
address2: [''],
city: ['', Validators.required],
zip: ['', Validators.required]
}),
shipping: this.fb.group({
firstName: ['', Validators.required],
lastName: ['', Validators.required],
address1: ['', Validators.required],
address2: [''],
city: ['', Validators.required],
zip: ['', Validators.required]
}),
});
html文件的一部分:
<form [formGroup]="profileForm" (ngSubmit)="onSubmit()">
<div class="row">
<div class="col">
<p class="form-row form-left">
<span class="input-wrapper">
<input type="text" class="form-control" formControlName="firstName" required>
</span>
</p>
<p class="form-row form-right">
<span class="input-wrapper">
<input type="text" class="form-control" formControlName="lastName" required>
</span>
</p>
...
<button type="submit" class="btn btn-primary order-btn" [disabled]="!profileForm.valid">Order</button>
您可以在ngOnInit
或ngAfterViewInit
上重置表单,但请确保在表单初始化之后进行此重置
ngAfterViewInit() {
//reset form controls
this.profileForm.reset();
//reset validators, explicitly
this.accountForm.setErrors(null)
}
如果重新设定整个表单的种子不会影响嵌套的组/数组,则将它们作为this.profileForm.controls['billing'].reset();
我建议尝试使用
profileForm.resetForm()