I have multiple dynamic FormGroup
s in my code.
Also, some FormGroup
s have a feature to add multiple FormGroup
s/FormControl
s.
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 FormControl
s.
How can I create dynamic FormControl
s 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
FormArray
ofFormGroup
s forposts
.And you'll create a
FormArray
ofFormControl
s 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.