Reputation: 543
For the life of me I cannot figure out how to get Angular 6 Reactive forms to play nice with dynamic checkboxes. I will try to post a simple senario.
lets say I have an AJAX call that returns the following type of data
{
"name": "Name1",
"items": [{type: "banna"}, {type: "apple"}]
},
{
"name": "Name2",
"items": [{type: "orange"}, {type: "strwberry"}]
}
I simple want to add 4 checkboxes, to the screen (which I can do many ways) but I dont know how to plug them up with reactive forms
I also need to rehydrate the form assuming it was an existing record from the database
How on this planet can this be done? Any example will do
Upvotes: 0
Views: 987
Reputation: 11
On your template file, make sure you have an ngModel two-way binding on the checkbox that is of type boolean
<mat-checkbox [(ngModel)]="isSubscribed[0].isChecked" color="accent">{{items[0].type}}</mat-checkbox>
Edit your data structure to include the values of those checkboxes
{
"name": "Name1",
"items": [{type: "banana", isChecked: false}, {type: "apple", isChecked: false}]
},
{
"name": "Name2",
"items": [{type: "orange", isChecked: false}, {type: "strawberry", isChecked: false}]
}
Upvotes: 0
Reputation: 692181
The model of the form doesn't have to match exactly with the structure of your object.
All you need to do is to create the appropriate structure in order to make it easy to edit it with checkboxes, and then, when you submit the form, transform it to the structure you want.
Before editing, transform
{
"name": "Name1",
"items": [{type: "banana"}, {type: "apple"}]
}
into
{
"name": "Name1",
fruits: {
banana: true,
apple: true,
strawberry: false,
orange: false
}
}
by setting each fruit to true if there is an item of that type in the original object.
Mapping checkboxes to these 4 fruits is now simple, since the value of a checkbox is true or false.
Suppose the user edits the object by checking/unchecking checkbowes, and thus turns it into
{
"name": "Name2",
fruits: {
banana: false,
apple: true,
strawberry: true,
orange: false
}
}
Now when submitting, you just need to transform that structure back into what you want:
{
"name": "Name2",
"items": [{type: "strawberry"}, {type: "apple"}]
}
by iterating through the keys of the fruits, filtering those that are true, and adding an item of that type to the array of items.
Upvotes: 1