我有一个角形反应形式,提交后我有以下代码:
(ngSubmit)="addVideo(); addVidForm.reset();"
我正在用#addVidForm
我还有一些自定义验证器/控件,与其他表单相比,它们是特殊的,我在重置表单时不会出现这种情况。
我的验证器如下:
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])
})
我还制作了一个函数,该函数只重置后端的表单并使用按钮调用它,而我遇到相同的错误。
不能完全确定这整个过程的哪一部分失败了。该字段是我在其他地方使用的常规输入。
答案 0 :(得分:0)
找到了另一个堆栈溢出线程,该线程在注释中描述了form.reset()函数实际执行的操作,该函数将所有值设置为null而不是其初始值。
我不想在重置时手动设置每个表单控件的值,因此我创建了一个函数,只需在提交时重新声明表单即可。像这样:
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])
})
}
答案 1 :(得分:0)
对于反应式表单,您需要使用[formGroup]属性绑定。它公开了reset()公共方法。
模板:
<form [formGroup]="registerForm">
.....
</form>
组件:
this.registerForm.reset();
this.registerForm.markAsPristine();
this.registerForm.markAsUntouched();
您还可以将“空值”传递给“表单值”。
this.registerForm.reset(this.registerForm.value);
答案 2 :(得分:-1)
通过以下方式在类中创建表单的元素引用。
@ViewChild('formRef') formRef;
form: FormGroup;
在组件类构造函数中构造您的表单
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
现在提交表单将导致表单清除,而不会留下任何验证错误。