When considering an approach similar to Netanel Basal's, it is essential to modify the submit function for smoother operation. One way to achieve this is by structuring a Form with values such as:
{
"otherControls": "",
"myChoices": [
false,
true,
false
]
}
Although the initial data may seem unattractive, the submit function can be adjusted to transform it into a more organized format:
submit(myForm) {
if (myForm.valid) {
const value = { ...myForm.value };
value.myChoices = this.checks
.filter((x, index) => myForm.value.myChoices[index])
.map(x => x.value);
this.result = value;
}
}
This modification will result in a cleaner output, like so:
{
"otherControls": "",
"myChoices": [
"value2"
]
}
While the submit process may become slightly more complex, the form structure itself becomes streamlined and intuitive:
<form *ngIf="myForm" [formGroup]="myForm" (submit)="submit(myForm)">
<div formArrayName="myChoices">
<div *ngFor="let choice of myForm.get('myChoices').controls; let i=index" class="col-md-2">
<label>
<input type="checkbox" [formControlName]="i">
{{checks[i].description}}
</label>
</div>
</div>
<button type="submit">submit</button>
</form>
This method eliminates the need for external functions and minimizes complications typically associated with dynamic forms. By setting up the form initially as:
initModelForm(): FormGroup {
return this._fb.group({
otherControls: [""],
myChoices: new FormArray(this.checks.map(x => new FormControl(false)))
});
}
For further reference, see this StackBlitz demo