2017-09-02 36 views
0

我有使用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顯示此問題的實際應用。

感謝您提供任何幫助。

+1

它不應該是這樣的。根據源代碼,「重置」會將表單標記爲未觸及且原始狀態。請參閱https://github.com/angular/angular/blob/master/packages/forms/src/model.ts#L1087 –

+0

我已更新答案,以包含[Stackblitz](https://stackblitz.com/編輯/ angular-vrrrqy)來演示問題的實際操作。你會注意到onSubmit調用了reset(),導致所有的輸入,其中有'驗證器'被觸摸和骯髒。謝謝! –

+0

不知何故,使用'ngSubmit'會中斷流程。我可以看到所有輸入都保持原樣+原始狀態,但錯誤仍在顯示。如果將提交按鈕更改爲'

回答

2

正如@Harry Ninh在評論中提到的那樣,使用常規按鈕而不是ngSubmit將修復此行爲。這是因爲,默認情況下,輸入爲invalidtouchedsubmitted時會顯示材料錯誤。有一個關於它的長話,here,但基本上,在窗體控件或表單組上調用reset()不會重置實際窗體,只是值。

您可以執行下列操作之一:

  1. 使用由@Harry寧
  2. 使用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(); 
    } 
} 
相關問題