While working with dynamic JSON data, I needed to create fields dynamically. For instance, if my JSON array contains 3 values, I would generate 3 input checkboxes dynamically as shown below:
<ng-template ngFor let-numberOfRow [ngForOf]="numberOfRows">
<mat-checkbox [formControlName]="numberOfRow.row" [value]="numberOfRow.row" [name]="numberOfRow.row">All</mat-checkbox>
</ng-template>
Currently, I am facing difficulties in creating a formBuilder for these fields. Can anyone guide me on how to declare formbuilder for dynamic fields?
public ngOnInit() {
this.myForm= this.fb.group(this.formFields);
}
public formFields() {
let empArr = [];
for (let val of this.myArrayList) {
empArr.push(val + ": ''");
}
let allFields = '{' + empArr.join(',') + '}';
return allFields;
}
The function above (formFields) will return a string in the format
{ allRow: '', firstRow: '', secondRow: '', thirdRow: '' }
.
Instead of statically declaring the form fields like
this.myForm= this.fb.group({ allRow: '', firstRow: '', secondRow: '', thirdRow: '' });
, I am looking for a way to declare them dynamically.