我有使用Reactive FormAngular 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元件角材料投入(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()
時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 present on the elements. Strangely they also have the
ng-pristine CSS class on them after the
reset()`。
什麼是最有效的方法來重置表單,包括清除/重置FormControl
值並將它們標記爲未被觸摸且不髒?它使用markAsUntouched()
還是markAsPristine()
?它是否使用setValue()
或reset()
以及特定的選項?目標是重置表單,就好像用戶第一次與它進行交互一樣。
更新:這是一個Stackblitz顯示此問題的實際應用。
感謝您提供任何幫助。
它不應該是這樣的。根據源代碼,「重置」會將表單標記爲未觸及且原始狀態。請參閱https://github.com/angular/angular/blob/master/packages/forms/src/model.ts#L1087 –
我已更新答案,以包含[Stackblitz](https://stackblitz.com/編輯/ angular-vrrrqy)來演示問題的實際操作。你會注意到onSubmit調用了reset(),導致所有的輸入,其中有'驗證器'被觸摸和骯髒。謝謝! –
不知何故,使用'ngSubmit'會中斷流程。我可以看到所有輸入都保持原樣+原始狀態,但錯誤仍在顯示。如果將提交按鈕更改爲'