Angular 反应式表单,formName.reset() 有效但抛出错误 'control.value is null' 并且所有字段都标记为 'red' 且无效?

Angular Reactive Forms, formName.reset() works but throws error 'control.value is null' and all fields are marked 'red' and invalid?

我有一个 angular 反应形式,在提交时我有这个代码:

(ngSubmit)="addVideo(); addVidForm.reset();"

我正在用 #addVidForm

标记我的主表单

我也有一些自定义 validators/controls,这与我拥有的另一种表格相比很特殊,在重置表格时不会发生这种情况。

我的验证器如下:

 static mustBeVimeo(control: AbstractControl) : ValidationErrors | null {

        if((control.value as string).startsWith("https://vimeo.com/")){ return null } else
        if((control.value as string).startsWith("http://vimeo.com/")){ return null }
        else { return { mustBeVimeo : true } }

}

这是我在后端的表格:

this.addVideoForm = new FormGroup({
      title: new FormControl('', [Validators.required, Validators.minLength(3), Validators.maxLength(50)]),
      description: new FormControl('', [Validators.required, Validators.minLength(5), Validators.maxLength(200)]),
      category: new FormControl('', [Validators.required]),
      link: new FormControl('', [Validators.required, AddVideoValidators.mustBeVimeo, Validators.maxLength(100)]),
      visibleToGuests: new FormControl(this.visibleToGuests, [Validators.required])
    })

我还制作了一个函数,它只是在后端重置表单并使用按钮调用它,但我遇到了同样的错误。

不完全确定整个事情的哪一部分失败了。该字段是我在其他地方使用的正常输入。

按以下方式在 class 中创建表单的元素引用。

@ViewChild('formRef') formRef;
form: FormGroup;

在组件 class 构造函数中构造您的表单

constructor() {
  this.form = new FormGroup({
    formControl1: new FormControl()
    // etc...
  })
}

然后将 #formRef 添加到模板表单标签。注意保留现有指令。

<form #formRef="ngForm"></form>

现在重置表单就像

一样简单
this.form.reset(); // Clears the Angular FormGroup without clearing validators.
this.formRef.resetForm(); // Clears the DOM form with validators

现在提交表单会清除表单,不会留下任何验证错误。

发现另一个堆栈溢出线程,其中在注释中描述了 form.reset() 函数实际执行的操作,即将所有值设置为空值而不是初始值。

我不想在重置时手动设置每个表单控件的值,所以我创建了一个函数,我只需在提交时重新声明表单。像这样:

  resetForm() {
    this.addVideoForm = new FormGroup({
      title: new FormControl('', [Validators.required, Validators.minLength(3), Validators.maxLength(50)]),
      description: new FormControl('', [Validators.required, Validators.minLength(5), Validators.maxLength(200)]),
      category: new FormControl('', [Validators.required]),
      link: new FormControl('', [Validators.required, AddVideoValidators.mustBeVimeo, Validators.maxLength(100)]),
      visibleToGuests: new FormControl(this.visibleToGuests, [Validators.required])
    })
  }

对于响应式表单,您需要使用 [formGroup] 属性绑定。它公开了 reset() public 方法。

模板:

<form [formGroup]="registerForm">
.....
</form>

分量:

this.registerForm.reset();
this.registerForm.markAsPristine();
this.registerForm.markAsUntouched();

您也可以将空值传递给表单值。

this.registerForm.reset(this.registerForm.value);