【发布时间】:2018-02-11 01:34:18
【问题描述】:
我有 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();
}
使用与各个 FormControl 元素相关联的 Angular Material 输入,并与 (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>
在FormGroupcontactForm 上调用reset() 时(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 classesng-invalid&&ng-touchedpresent on the elements. Strangely they also have theng-pristineCSS class on them after thereset()`。
重置表单的最有效方法是什么,包括清除/重置FormControl 值并将它们标记为未触摸且未脏?是使用markAsUntouched() 还是markAsPristine()?是使用带有特定选项的setValue() 或reset() 吗?目标是重置表单,就像用户第一次与之交互一样。
更新:这是一个Stackblitz,显示了这个问题的实际效果。
感谢您提供的任何帮助。
【问题讨论】:
-
不应该这样。根据源代码,
reset会将表单标记为未触及和原始。见github.com/angular/angular/blob/master/packages/forms/src/… -
我已更新答案以包含 Stackblitz 以演示实际问题。您会注意到 onSubmit 调用了 reset(),导致所有具有
Validators的输入都被触摸并变脏。谢谢! -
不知何故使用
ngSubmit会破坏流程。我可以看到所有输入未触及+原始,但错误仍然存在。如果您将提交按钮更改为<button type="button" (click)="onSubmit()"之类的东西,它将起作用
标签: angular angular-material2 angular-reactive-forms