I have a form that contains a list of checkboxes for the user to check and then when the user submit the form, it should submit the list of checkboxes as an array of objects. In
It's an aproach like Netanel Basal (only change the submit function). The things goes more fluid if we think in a Form who value can be like e.g.
{
"otherControls": "",
"myChoices": [
false,
true,
false
]
}
Well, we don't want this ugly data, but we can, in submit write some like
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;
}
}
And "result" will be,e.g.
{
"otherControls": "",
"myChoices": [
"value2"
]
}
Well, its true that we are complex the "submit", but in another hand, our form becomes like
NOT externals function, not fight agains remove at push,etc Well, the only is create the form like
initModelForm(): FormGroup {
return this._fb.group({
otherControls: [""],
myChoices: new FormArray(this.checks.map(x => new FormControl(false)))
});
}
See stackblitz