Skip to content

Instantly share code, notes, and snippets.

@park-brian
Created June 19, 2018 17:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save park-brian/73f298b467fe351ad0d00c961a3ce005 to your computer and use it in GitHub Desktop.
Save park-brian/73f298b467fe351ad0d00c961a3ce005 to your computer and use it in GitHub Desktop.
Recursive FormBuilder which returns an AbstractControl
import { AbstractControl, FormArray, FormControl, FormGroup } from '@angular/forms';
/**
* Creates a nested FormGroup, FormArray, or FormControl with validators
* from a given object
*/
export const createFormObject = (initial: any): AbstractControl => {
if (Array.isArray(initial)) {
// detemine if array contains ValidatorFn or ValidatorFn[]
// eg: use same syntax as formBuilder
const isFn = obj => typeof obj === 'function';
const hasValidators = initial.some(isFn) ||
initial.filter(Array.isArray).some(isFn);
if (hasValidators)
return new FormControl(...initial);
else return new FormArray(
initial.map(val => this.createFormObject(val))
);
}
// return a FormGroup for objects
else if (typeof initial === 'object' && initial !== null)
return new FormGroup(
Object.keys(initial).reduce((acc, key) => ({
...acc,
[key]: this.createFormObject(initial[key])
}), {})
);
// otherwise, return a FormControl
return new FormControl(initial);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment