当我第一次加载页面时,表单显示如下
但是在我成功创建公告后,我用this.announcementCreateForm.reset()
代码重设了页面,并按照以下方式重设了
我在buildAnnouncementForm()
期间调用了以下方法ngOnInit()
private buildAnnouncementForm() {
this.announcementCreateForm = this.fb.group({
announcementTitle: ['', [Validators.required]],
announcementText: '',
announcementFor: ['', [Validators.required]],
announcementType: ['', [Validators.required]],
announcementFromDate: [this.announcementFromDate, Validators.required],
announcementToDate: [this.announcementToDate, Validators.required]
});
}
我在reset
之后调用success
resetAnnouncementPage() {
if (this.announcementCreateForm.valid) {
console.log("Reset...");
this.announcementCreateForm.reset();
this.announcementCreateForm.markAsPristine();
//this.announcementCreateForm.markAsUntouched();
}
}
我的重置,想让我携带加载时的样子吗。怎么做?
答案 0 :(得分:2)
如果您想将表单还原为初始状态,请将该状态存储为一个值,并在您想重置表单时使用它来设置表单值,
不要执行form.reset()
,它甚至会从from控件中删除空字符串。
initialFormValue = {
announcementTitle: '',
announcementText: '',
announcementFor: '',
announcementType: '',
announcementFromDate: this.announcementFromDate,
announcementToDate: this.announcementToDate
}
resetAnnouncementPage() {
if (this.announcementCreateForm.valid) {
console.log("Reset...");
this.announcementCreateForm.setValue(this.initialFormValue);
this.announcementCreateForm.markAsPristine();
}
}
修改
您还可以在进行表单reset()
时传递重置值。
private _initialValue
private buildAnnouncementForm() {
this.announcementCreateForm = this.fb.group({
announcementTitle: ['', [Validators.required]],
announcementText: '',
announcementFor: ['', [Validators.required]],
announcementType: ['', [Validators.required]],
announcementFromDate: [this.announcementFromDate, Validators.required],
announcementToDate: [this.announcementToDate, Validators.required]
});
this._initialValue = this.announcementCreateForm.value
}
resetAnnouncementPage() {
if (this.announcementCreateForm.valid) {
this.announcementCreateForm.reset(this._initialValue);
}
}
答案 1 :(得分:1)
您必须将其标记为原始且未更改,然后重新验证。
this.announcementCreateForm.reset();
this.announcementCreateForm.markAsPristine();
this.announcementCreateForm.markAsUntouched();
this.announcementCreateForm.updateValueAndValidity();
答案 2 :(得分:0)
我遵循了这些步骤并实现了
将formDirective添加到表单并将其传递给我的onSubmit
方法
<form #formDirective="ngForm" (ngSubmit)="onSubmit(formDirective)" [formGroup]="announcementCreateForm">
将formDirective
参数传递给我的reset
方法,并将reset
formDirective
传递给我,然后我reset
传递了form
resetAnnouncementPage(formDirective:FormGroupDirective) {
if (this.announcementCreateForm.valid) {
formDirective.resetForm();
this.announcementCreateForm.reset();
}
}