表单重置后重置验证(反应式表单)
reset validations after form reset(ReactiveForms)
HTML:
<form [formGroup]="locationForm" #myForm="ngForm" class="formContainer">
<div class="buttonContainer">
<section class="btn1">
<button
(click)="addAnotherMethod()"
mat-raised-button
color="primary"> Add another method </button>
</section>
<section>
<button
(click)="addAnotherLocation()"
mat-raised-button
color="primary"> Add another location </button>
</section>
</div>
.TS 文件
@ViewChild('myForm') currentLocationForm;
addAnotherLocation(): void{
if(this.locationForm.valid){
//send data to redux
}))
}
this.currentLocationForm.resetForm()
}
addAnotherMethod: void {
if(this.locationForm.valid){
//send data to redux
}))
}
this.currentLocationForm.resetForm()
}
使用上面的代码,我可以在数据发送到 redux 后重置表单,但重置后,新表单中的验证错误消息会出现,要求填写必填字段。我需要帮助使用正确的方法来重置此表单并在显示新表单时清除验证。我可能还使用了错误的方法来调用两个按钮功能。
谢谢。
您的表单中有 2 个内容:FormGroup
和 FormGroupDirective
。要让错误消失,您需要重置它们:
this.currentLocationForm.resetForm();
this.locationForm.reset();
有关原因的更多详细信息,请参阅 post。
如果您希望将表单重置为原始状态。意思是在任何东西被触动之前
Mark as Pristine 将是您最好的选择。
实际上 markAsPristine
会按照您的预期进行,但也会根据表单值重新计算有效性。
Reset 既可以清除表格又可以将其标记为从未被触摸过,也就是 Pristine
所以在代码中你会做类似的事情。
this.locationForm.reset();
这会将 fromGroup 及其所有子项标记为原始。
这将有效地重置您的表单并且不应该有任何验证错误。
如果有帮助请告诉我!
HTML:
<form [formGroup]="locationForm" #myForm="ngForm" class="formContainer">
<div class="buttonContainer">
<section class="btn1">
<button
(click)="addAnotherMethod()"
mat-raised-button
color="primary"> Add another method </button>
</section>
<section>
<button
(click)="addAnotherLocation()"
mat-raised-button
color="primary"> Add another location </button>
</section>
</div>
.TS 文件
@ViewChild('myForm') currentLocationForm;
addAnotherLocation(): void{
if(this.locationForm.valid){
//send data to redux
}))
}
this.currentLocationForm.resetForm()
}
addAnotherMethod: void {
if(this.locationForm.valid){
//send data to redux
}))
}
this.currentLocationForm.resetForm()
}
使用上面的代码,我可以在数据发送到 redux 后重置表单,但重置后,新表单中的验证错误消息会出现,要求填写必填字段。我需要帮助使用正确的方法来重置此表单并在显示新表单时清除验证。我可能还使用了错误的方法来调用两个按钮功能。 谢谢。
您的表单中有 2 个内容:FormGroup
和 FormGroupDirective
。要让错误消失,您需要重置它们:
this.currentLocationForm.resetForm();
this.locationForm.reset();
有关原因的更多详细信息,请参阅
如果您希望将表单重置为原始状态。意思是在任何东西被触动之前
Mark as Pristine 将是您最好的选择。
实际上 markAsPristine
会按照您的预期进行,但也会根据表单值重新计算有效性。
Reset 既可以清除表格又可以将其标记为从未被触摸过,也就是 Pristine
所以在代码中你会做类似的事情。
this.locationForm.reset();
这会将 fromGroup 及其所有子项标记为原始。 这将有效地重置您的表单并且不应该有任何验证错误。
如果有帮助请告诉我!