I'm currently working on creating an Angular form with predefined key names and values that remain constant. While I have successfully built a form, the output format is not exactly what I require.
keysToChange = ['key1', 'key2', 'key3', 'key4']
export interface PatchForm {
[x: string]: FormControl<string | null>
date: FormControl<string | null>
}
patchForm = this.fb.group({
keysToChange: this.fb.array<FormGroup<PatchForm>>([]),
})
initializeForm() {
this.keysToChange.forEach((key) => {
const formGroup = this.fb.nonNullable.group({
[key]: new FormControl(''),
date: new FormControl(''),
})
this.patchForm.controls.keysToChange.push(formGroup)
})
}
I get the following output:
{
"keysToChange": [
{
"key1": "",
"date": ""
},
{
"key2": "",
"date": ""
},
{
"key3": "",
"date": ""
},
{
"key4": "",
"date": ""
}
]
}
However, I need something more like this:
export interface PatchForm {
id: FormControl<string | null>
date: FormControl<string | null>
}
Then I would like the output to be structured as follows:
{
"key1": {
"id": "string",
"date": "2024-04-03T11:23:05.499Z"
},
"key2": {
"id": "string",
"date": "2024-04-03T11:23:05.499Z"
},
"key3": {
"id": "string",
"date": "2024-04-03T11:23:05.499Z"
},
"key4": {
"id": "string",
"date": "2024-04-03T11:23:05.499Z"
}
}
The main issue I am facing lies in creating types and initializing the form because my eslint does not allow the unsafe use of type 'any', and I am struggling to understand how to set keys for each FormGroup.