Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

angular - Angular2: How do you mark FormGroup control dirty via `patchValue()`

I am updating a Reactive FormGroup control value from my component via patchValue.

Ex:

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

This works great and triggers a valueChanges event, however this control's dirty property is still false.

I need the incidentDate control to be dirty so my validation logic knows to run against this control.

How do I update the value of a control from my component AND indicate that it is dirty?

Here is my validation logic:

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] + ' ';
        }
      }
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I usually do this:

this.formControl.markAsDirty()

Or in your case it could be:

this.myForm.get('incidentDate').markAsDirty()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...