我Reactive Form使用Angular Material输入(mdInput
),使用FormBuilder
按以下方式初始化:
contactForm: FormGroup;
this.contactForm = this.fb.group({
name: ['', [Validators.required, Validators.maxLength(128)]],
email: ['', [Validators.required, Validators.email]],
subject: ['', [Validators.required, Validators.maxLength(128)]],
message: ['', [Validators.required, Validators.maxLength(1000)]]
});
onSubmit(): void {
this.resetForm();
}
private resetForm(): void {
this.contactForm.reset();
}
将Angular Material输入与相应的FormControl元素关联,并挂钩到(ngSubmit)
:
<form [formGroup]="contactForm" (ngSubmit)="onSubmit()">
<md-input-container>
<input mdInput formControlName="name" placeholder="Name">
</md-input-container>
<button type="submit" md-raised-button [disabled]="contactForm.invalid">Submit</button>
在reset()
FormGroup
上调用contactForm
时(this.contactForm.reset(), the form elements values are successfully cleared/replaced with empty strings, but the elements are both immediately dirty and touched with CSS classes
ng-invalid &&
ng-touching {{1} } NG-原始present on the elements. Strangely they also have the
复位()`。
重置表单的最有效方法是什么,包括清除/重置CSS class on them after the
值并将其标记为未触及且不脏?是利用FormControl
还是markAsUntouched()
?是否使用markAsPristine()
或setValue()
具有特定选项?目标是重置表单,就像用户第一次与它进行交互一样。
更新:以下是显示此问题的Stackblitz。
感谢您提供任何帮助。
答案 0 :(得分:2)
正如@Harry Ninh在评论中所提到的,使用常规按钮代替ngSubmit
将修复行为。这是因为,默认情况下,当输入为invalid
且touched
或submitted
时,会显示材质错误。有一个关于它的长线程here,但基本上,在表单控件或表单组上调用reset()
不会重置实际表单,只重置值。
您可以执行以下操作之一:
ViewChild
访问FormGroupDirective
并重置。见这里:
@ViewChild(FormGroupDirective) myForm;
contactForm: FormGroup;
constructor(private fb: FormBuilder) {
this.createForm();
}
private createForm(): void {
this.contactForm = this.fb.group({
name: ['', [Validators.required, Validators.maxLength(128)]],
email: ['', [Validators.required, Validators.email]],
subject: ['', [Validators.required, Validators.maxLength(128)]],
message: ['', [Validators.required, Validators.maxLength(1000)]]
});
}
onSubmit(): void {
this.resetForm();
}
private resetForm(): void {
if (this.myForm) {
this.myForm.resetForm();
}
}