When to use FormGroup vs. FormArray?

前端 未结 4 1719
庸人自扰
庸人自扰 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:51

    In order to create a reactive forms, a parent FormGroup is a must. This FormGroup can further contain formControls, child formGroups or formArray

    FormArray can further contain array of formControls or a formGroup itself.

    When should we use formArray?

    Please read this beautiful post which explains the usage of formArray

    The interesting example in that blog is about the trips formGroup

    The structure of trips formGroup using formControl and formArray would look something like:

    this.tripForm = this.fb.group({
        name: [name, Validators.required],
         cities: new FormArray(
           [0] ---> new FormGroup({
               name: new FormControl('', Validators.required),
                   places: new FormArray(
                      [0]--> new FormGroup({
                          name: new FormControl('', Validators.required),
                             }),
                          [1]--> new FormGroup({
                             name: new FormControl('', Validators.required),
                          })
                      )
                  }), 
           [1] ---> new FormGroup({
               name: new FormControl('', Validators.required),
               places: new FormArray(
                   [0]--> new FormGroup({
                       name: new FormControl('', Validators.required),
                   }),
                   [1]--> new FormGroup({
                       name: new FormControl('', Validators.required),
                   })
                   )
          }))
    })
    

    Do not forget to play with this DEMO, and notice the usage of array for cities and places of a trip.

提交回复
热议问题