2016-10-01 60 views
9

我正在通過patchValue從我的組件更新一個反應FormGroup控制值。Angular2:你如何通過`patchValue()標記FormGroup控件髒

例:

this.myForm.patchValue({incidentDate:'2016-09-12'); 

這個偉大的工程,並觸發valueChanges事件,但這種控制的dirty屬性仍然false

我需要incidentDate控制爲dirty,所以我的驗證邏輯知道要對此控件運行。

如何更新從我的部件的控制的價值,並表明它是髒的?

這裏是我的驗證邏輯:

onValueChanged(data?: any) { 
    if (!this.myForm) { 
     return; 
    } 
    const form = this.myForm; 
    for (const field in this.formErrors) { 
     // clear previous error message (if any) 
     this.formErrors[field] = ''; 
     const control = form.get(field); 
     if (control && control.dirty && !control.valid) { 
     const messages: any = this.validationMessages[field]; 
     for (const key in control.errors) { 
      this.formErrors[field] += messages[key] + ' '; 
     } 
     } 
    } 
} 

回答

19

我經常這樣做:

this.formControl.markAsDirty() 

或者在你的情況可能是:

(this.myForm.controls['incidentDate'] as FormControl).markAsDirty() 
+0

你是我的朋友,是男人。好奇,你在哪裏發現這個記錄?這是沒有在https://angular.io/docs/ts/latest/api/forms/index/FormControl-class.html被發現在那裏 – rynop

+2

我很經常來到這裏https://github.com/angular/angular /blob/master/modules/%40angular/forms/src/model.ts lol –

+0

當人們直接將我帶入源代碼時,我喜歡它。 – Hinrich

1

如果你有一組或陣列,你需要標記爲髒你可以使用這個

export class Helpers { 
/** 
    * Loop and touch all it has 
    * 
    * @param {FormGroup} formGroup 
    * @param func << function name: [markAsTouched, markAsUntouched, markAsDirty, markAsPristine, markAsPending 
    * @param opts 
    * 
    */ 
    public static touchAll(formGroup: FormGroup|FormArray, func = 'markAsDirty', opts = {onlySelf: false}): void { 
    mapValues(formGroup.controls, (c, i) => { 
     if (c instanceof FormGroup || c instanceof FormArray) 
     Helpers.touchAll(c, func, opts); 
     else 
     c[func](opts); 
    }) 
    } 
} 

您可以使用SuperForm npm package爲您做到這一點。

相關問題