Angular 2: Iterate over reactive form controls

前端 未结 9 746
遥遥无期
遥遥无期 2020-12-02 07:23

I would like to markAsDirty all the controls inside of a FormGroup.

相关标签:
9条回答
  • 2020-12-02 07:55

    Based on @Keenan Diggs answer I wrote a generic function to traverse a flat or nested form, which accepts an operation to be performed against each form control:

    export function traverseForm(
        form: FormGroup | FormArray, 
        fn: ((c: AbstractControl, name: string, path: string) => void),
        initialPath: string = '') {
      Object.keys(form.controls).forEach((key: string) => {
        const abstractControl = form.controls[key];
        const path = initialPath ? (initialPath + '.' + key) : key;
        fn(abstractControl, key, path);
        if (abstractControl instanceof FormGroup || abstractControl instanceof FormArray) {
            traverseForm(abstractControl, fn, path);
        }
      });
    } 
    

    To be used like this:

    const markAsDirty = (ctrl: AbstractControl) => {
       if (!(abstractControl instanceof FormGroup) && !(abstractControl instanceof FormArray)) {
          abstractControl.markAsDirty();
       }
    }
    traverseForm(form, markAsDirty);
    
    0 讨论(0)
  • 2020-12-02 07:56

        Object.keys( this.registerForm.controls).forEach(key => {
           this.registerForm.controls[key].markAsDirty();
        });

    0 讨论(0)
  • 2020-12-02 07:56

    This is what working for me

    private markFormGroupTouched(formGroup: FormGroup) {
      Object.keys(formGroup.controls).forEach((key) => {
        const control = formGroup.controls[key];
        control.markAsDirty();
        if ((control instanceof FormGroup)) {
          this.markFormGroupTouched(control);
        }
      });
    }
    
    0 讨论(0)
提交回复
热议问题