When to use FormGroup vs. FormArray?

前端 未结 4 1715
庸人自扰
庸人自扰 2020-11-27 11:50

FormGroup:

A FormGroup aggregates the values of each child FormControl into one object, with each control name as the key.

4条回答
  •  自闭症患者
    2020-11-27 12:35

    From angular documentation you can see that

    FormArray is an alternative to FormGroup for managing any number of unnamed controls. As with form group instances, you can dynamically insert and remove controls from form array instances, and the form array instance value and validation status is calculated from its child controls. However, you don't need to define a key for each control by name, so this is a great option if you don't know the number of child values in advance.

    Let me show you their example and try to explain how I understand this. You can see source here

    Imagine a form witch has following fields

      profileForm = this.fb.group({
        firstName: ['', Validators.required],
        lastName: [''],
        address: this.fb.group({
          street: [''],
          city: [''],
          state: [''],
          zip: ['']
        }),
        aliases: this.fb.array([
          this.fb.control('')
        ])
      });
    

    Here we have firstName, lastName, address and aliases All field together are form group so we wrap everything in group. At the same time address is like a subgroup so we wrap it in another group (You can look at template for better understanding)! Every form control here hes key except aliases and it means that you can push in it values as much as you want like simple array using formBuilder methods like push.

    This is how I understand it, hope it helps someone.

提交回复
热议问题