FormGroup 和 FormArray 有什么区别?什么时候用什么?

May*_*ore 4 angular angular-reactive-forms angular-forms formarray

FormGroup我的代码中有多个 dynamic 。

此外,某些FormGroups 具有添加多个FormGroups/ FormControls 的功能。

因此,在FormGroup动态创建时,我已经使用FormBuilder.group()了多个组,但我想为其创建一个数据数组FormControl

如何FormControl为这个数据对象数组创建动态?

Sid*_*era 8

将响应式表单视为围绕您的数据模型的表单。因此,响应式表单将与您的数据模型的方式完全对应。

例如,考虑这个数据模型:

{
  id: 1,
  name: "Leanne Graham",
  username: "Bret",
  email: "Sincere@april.biz",
  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]
    }
  ]]
}
Run Code Online (Sandbox Code Playgroud)

现在这里是这个数据模型的 Reactive Form 的总体要点。

  1. 如果属性的值是一个对象(如address),那么我们将为FormGroup它创建一个。
  2. 如果属性的值是一个数组(如posts),那么我们将为FormArray它创建一个。
  3. 如果一个属性的值是一个原始的(如idnameisVerified等等),我们会为它创建一个FormControl。

这里的所有都是它的。这一切都非常简单。

现在你可能会想:

你会为了什么而创造posts

你会为了什么而创造commentIds

所以如果你回到上面的规则:

您将创建一个FormArrayof FormGroups for posts

您将创建一个FormArrayof FormControls for commentIds

这应该回答你的主要问题。

PS:我们需要更多信息来帮助您获取有关如何在此处执行操作的确切代码。