Reactive Forms - mark fields as touched

后端 未结 19 1577
旧时难觅i
旧时难觅i 2020-12-04 23:15

I am having trouble finding out how to mark all form\'s fields as touched. The main problem is that if I do not touch fields and try to submit form - validation error in not

19条回答
  •  情书的邮戳
    2020-12-04 23:40

    A solution without recursion

    For those worried about performance, I've come up with a solution that doesn't use recursion, although it still iterates over all controls in all levels.

     /**
      * Iterates over a FormGroup or FormArray and mark all controls as
      * touched, including its children.
      *
      * @param {(FormGroup | FormArray)} rootControl - Root form
      * group or form array
      * @param {boolean} [visitChildren=true] - Specify whether it should
      * iterate over nested controls
      */
      public markControlsAsTouched(rootControl: FormGroup | FormArray,
        visitChildren: boolean = true) {
    
        let stack: (FormGroup | FormArray)[] = [];
    
        // Stack the root FormGroup or FormArray
        if (rootControl &&
          (rootControl instanceof FormGroup || rootControl instanceof FormArray)) {
          stack.push(rootControl);
        }
    
        while (stack.length > 0) {
          let currentControl = stack.pop();
          (Object).values(currentControl.controls).forEach((control) => {
            // If there are nested forms or formArrays, stack them to visit later
            if (visitChildren &&
                (control instanceof FormGroup || control instanceof FormArray)
               ) {
               stack.push(control);
            } else {
               control.markAsTouched();
            }
          });
        }
      }
    

    This solution works form both FormGroup and also FormArray.

    You can play around with it here: angular-mark-as-touched

提交回复
热议问题