I'm struggling with populating form fields from an array. My initial approach was to input the array into a single component that would manage the form instead of creating multiple forms. However, I can't seem to make it work. Any assistance would be greatly appreciated! Despite my efforts on various platforms like Google, Stack Overflow, and Medium, I couldn't find a solution. You can also check out an example on Plunkr here.
In the TypeScript file:
public demoForm: FormGroup;
public arrayItems: data = [];
private formFields = ["Sku", "Title"];
constructor(private _formBuilder: FormBuilder) {
this.demoForm = this._formBuilder.group({
demoArray: this._formBuilder.array([])
});
}
ngOnInit() {
this.formFields.map(field => {
this.arrayItems.push({ title: field });
this.demoArray.push(this._formBuilder.control(''));
});
}
get demoArray() {
return this.demoForm.get("demoArray") as FormArray;
}
In the template:
<form [formGroup]="demoForm">
<div formArrayName="demoArray"
*ngFor="let arrayItem of arrayItems; let i=index">
<input type="checkbox"[formControl]="demoArray[i]">
<label>{{arrayItem.title}}</label>
</div>
</form>
Thank you for your help!