Created
June 19, 2018 17:39
-
-
Save park-brian/73f298b467fe351ad0d00c961a3ce005 to your computer and use it in GitHub Desktop.
Recursive FormBuilder which returns an AbstractControl
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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