Angular2:你如何通过`patchValue()`标记FormGroup控件脏

ryn*_*nop 18 angular

我正在FormGroup通过patchValue从我的组件更新Reactive 控件值.

例如:

this.myForm.patchValue({incidentDate:'2016-09-12');
Run Code Online (Sandbox Code Playgroud)

这很好用并触发一个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] + ' ';
        }
      }
    }
}
Run Code Online (Sandbox Code Playgroud)

Har*_*inh 37

我经常这样做:

this.formControl.markAsDirty()
Run Code Online (Sandbox Code Playgroud)

或者在你的情况下它可能是:

this.myForm.get('incidentDate').markAsDirty()
Run Code Online (Sandbox Code Playgroud)

  • 我需要在`markAsDirty()`之后添加对`this.formControl.updateValueAndValidity()`的调用以使其正常工作. (4认同)
  • 我经常来这里https://github.com/angular/angular/blob/master/modules/%40angular/forms/src/model.ts大声笑 (2认同)