Advertisement
attilan

Form utils

Jun 1st, 2022
897
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import { AbstractControl } from '@angular/forms';
  2.  
  3. type ControlChangeOptions = {
  4.   onlySelf?: boolean;
  5.   emitEvent?: boolean;
  6. };
  7.  
  8. export class FormUtils {
  9.  
  10.   static readonly defaultOptions: ControlChangeOptions = {
  11.     onlySelf: false,
  12.     emitEvent: true,
  13.   };
  14.  
  15.   /**
  16.    * Updates every value of given control array
  17.    */
  18.   static patchControls<T>(
  19.     controls: AbstractControl[],
  20.     value: T,
  21.     options = FormUtils.defaultOptions
  22.   ): void {
  23.     if (!Array.isArray(controls)) {
  24.       return;
  25.     }
  26.  
  27.     controls.forEach(control => control.patchValue(value, options));
  28.   }
  29.  
  30.   /**
  31.    * Disables each control in the array
  32.    */
  33.   static disableControls(
  34.     controls: AbstractControl[],
  35.     options = FormUtils.defaultOptions
  36.   ): void {
  37.     if (!Array.isArray(controls)) {
  38.       return;
  39.     }
  40.  
  41.     controls.forEach(control => control.disable(options));
  42.   }
  43.  
  44.   /**
  45.    * Enables each control in the array
  46.    */
  47.   static enableControls(
  48.     controls: AbstractControl[],
  49.     options = FormUtils.defaultOptions
  50.   ): void {
  51.     if (!Array.isArray(controls)) {
  52.       return;
  53.     }
  54.  
  55.     controls.forEach(control => control.enable(options));
  56.   }
  57.  
  58. }
  59.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement