Search code examples
angularangular-reactive-formsangular-formsformarray

What is the difference between FormGroup and FormArray? When to use what?


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?


Solution

  • 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]
        }
      ]]
    }
    

    Now here's the over-all gist of what Reactive Form would be like for this data-model.

    1. If the value of a property is an Object(like address), then we'll create a FormGroup for it.
    2. If the value of a property is an Array(like posts), then we'll create a FormArray for it.
    3. If the value of a property is a primitive(like id, name, isVerified etc), we'll create a FormControl for it.

    That's all there is to it. It's all pretty straight-forward.

    Now you might think:

    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 of FormGroups for posts.

    And you'll create a FormArray of FormControls for commentIds.

    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.