【问题标题】:Angular2: How do you mark FormGroup control dirty via `patchValue()`Angular2:如何通过`patchValue()` 将 FormGroup 控件标记为脏
【发布时间】:2017-02-09 16:50:50
【问题描述】:

我正在通过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] + ' ';
        }
      }
    }
}

【问题讨论】:

    标签: angular


    【解决方案1】:

    我通常这样做:

    this.formControl.markAsDirty()
    

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

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

    【讨论】:

    【解决方案2】:

    如果你有一个组或数组需要标记为脏,你可以使用它

    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 为您执行此操作。

    【讨论】:

      【解决方案3】:

      在 FormGroup 中标记为脏控件(只有那些有值的控件)

        markDirtyAllControlsWithValue(form: FormGroup): void {
          const recursiveFunc = (formGroup: FormGroup) => {
            Object.keys(formGroup.controls).forEach(field => {
              const control = formGroup.get(field);
              if (control.value !== null && control.value !== undefined && control.value !== '') {
                control.markAsDirty();
              }
              if (control instanceof FormGroup) {
                recursiveFunc(control);
              }
            });
          };
          recursiveFunc(form);
        }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-10-08
        • 2018-06-02
        • 1970-01-01
        • 1970-01-01
        • 2011-04-04
        • 1970-01-01
        • 1970-01-01
        • 2017-04-16
        相关资源
        最近更新 更多