form.utils.ts 752 Bytes
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
import { FormGroup, AbstractControl, FormArray } from '@angular/forms';

export class FormUtils {
  public static touchAllFields(group: FormGroup): void {
    Object.keys(group.controls).forEach(controlName => {
      const control: AbstractControl = group.get(controlName);
      if (control instanceof FormArray) {
        const arr = control as FormArray;
        for (let i = 0; i < arr.length; ++i) {
          FormUtils.touchAllFields(arr.at(i) as FormGroup);
        }
      } else if (control instanceof FormGroup) {
        FormUtils.touchAllFields(control);
      } else {
        control.markAsTouched({ onlySelf: true });
      }
    });
  }

  public static safeTrim(value: string): string {
    return value ? value.trim() : value;
  }
}