Angular 6 Material 表单重置导致出现验证错误

Angular 6 Material form reset makes Validation error appear

当我第一次加载页面时,表单显示如下

但是在我成功创建公告后,我用 this.announcementCreateForm.reset() 代码重置了页面,它重置了下面的方式

我在 ngOnInit()

期间调用了以下方法 buildAnnouncementForm()
 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]
    });
  }

我在success

之后调用了reset方法
resetAnnouncementPage() {
    if (this.announcementCreateForm.valid) {
      console.log("Reset...");
      this.announcementCreateForm.reset();
      this.announcementCreateForm.markAsPristine();
      //this.announcementCreateForm.markAsUntouched();
    }
  }

我的重置,想让我把表格变成加载时的样子..怎么办?

如果您想将表单恢复到初始状态,请将该状态存储在一个值中,并在您想要重置表单时使用它来设置表单值, 不要做 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);
    }

}

我按照这些步骤实现了它

将 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();
    }
  }