I have multiple dynamic FormGroups in my code.
Also, some FormGroups have a feature to add multiple FormGroups/FormControls.
So while creating FormGroup dynamically I have used FormBuilder.group() but for multiple groups, there is an array of data for which I want to create FormControls.
How can I create dynamic FormControls for this array of data objects?
Think of Reactive Forms as forms around your data model. So a Reactive Form would correspond exactly to the way your data model is.
Consider this data-model for example:
{
id: 1,
name: "Leanne Graham",
username: "Bret",
email: "[email protected]",
isVerified: false,
address: {
street: "Kulas Light",
suite: "Apt. 556",
city: "Gwenborough",
zipcode: "92998-3874",
},
phone: "1-770-736-8031 x56442",
website: "hildegard.org",
posts: [[
{
userId: 1,
id: 1,
title: "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
body: "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto",
commentIds: [1, 2, 3, 4, 5]
}, {
userId: 1,
id: 2,
title: "qui est esse",
body: "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla",
commentIds: [6, 7, 8, 9, 10]
}
]]
}
address), then we'll create a FormGroup for it.posts), then we'll create a FormArray for it.id, name, isVerified etc), we'll create a FormControl for it.That's all there is to it. It's all pretty straight-forward.
What will you create for
posts?What will you create for
commentIds?
So if you go back to the rules above:
You'll create a
FormArrayofFormGroups forposts.And you'll create a
FormArrayofFormControls forcommentIds.
This should answer your main question.
PS: We'll need more information to help you out with the exact code on how to do what you're trying to do here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With