Created
March 24, 2022 23:30
-
-
Save JeanPaulll/e5d1266c71f8ae623f1be00da78b99d4 to your computer and use it in GitHub Desktop.
Convert a DTO to FormBuilder
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
static toForm(data: any, nullFields?: boolean, formBuilder: FormBuilder = new FormBuilder()): AbstractControl { | |
if (!data) { | |
return formBuilder.control(null); | |
} | |
/** | |
* Se o data for array, percorre-o adicionando recursivamente | |
*/ | |
if (Array.isArray(data)) { | |
const form = formBuilder.array([]); | |
data.forEach(value => { | |
form.push(this.toForm(value, nullFields, formBuilder)); | |
}); | |
return form; | |
} | |
/** | |
* Se o data for objeto, cria um formGroup e verifica se tem valores que são objetos (ou array) | |
* e chama a função recursivamente enviando o valor até completar | |
*/ | |
if (typeof data === 'object') { | |
const form = nullFields ? formBuilder.group({}) : formBuilder.group(data); | |
Object.entries(data).reduce((acc, [key, value]) => { | |
if (typeof data === 'object') { | |
form.setControl(key, this.toForm(value, nullFields, formBuilder)); | |
} else if (nullFields) { | |
form.setControl(key, formBuilder.control(null)); | |
} | |
return acc; | |
}, {}); | |
return form; | |
} | |
/** | |
* Se o data não for objeto ou array, retorna um control simples | |
*/ | |
return formBuilder.control(nullFields ? null : data); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
:)