Angular 2: Iterate over reactive form controls

前端 未结 9 747
遥遥无期
遥遥无期 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);
    

提交回复
热议问题