I was creating fields dynamically based on Json. For example if my json array has 3 value then i will create 3 input checkbox dynamically like below
<ng-template ngFor let-numberOfRow [ngForOf]="numberOfRows">
<mat-checkbox [formControlName]="numberOfRow.row" [value]="numberOfRow.row" [name]="numberOfRow.row">All</mat-checkbox>
</ng-template>
now i m trying to create formBuilder for this fields like below but its not working. Could someone please tell me 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;
}
basically the above formFields function will return string like this { allRow: '', firstRow: '', secondRow: '', thirdRow: '' }
so instead if declaring statically this.myForm= this.fb.group({ allRow: '', firstRow: '', secondRow: '', thirdRow: '' }); i want to declare the fields dynamically.
formFields()? First of all if you want an object, create an object Secondly never try creating json manually, it is error prone , more work than needed and there are serializers in most languages to convert objects to json