0
votes

This is my form:

  this.addForm = this.formBuilder.group({
    details: this.formBuilder.array([]),
  });

I am calling this function to push control

 nestedFormGroupDetails(control) {
    control.push(
      this.formBuilder.group({
        name: ['', [Validators.required]],
        age: ['', [Validators.required]]
      }));

    **// based on scenario, I want to insert new control. ex. occupation
    this.detailsFormArray.insert(0, [...])  // how to add abstract control here**
  }

 get detailsFormArray() {
    return this.addForm.get('details') as FormArray
 }

Pls suggest me whether I am doing it right way and also pls advise how can I insert/push new control in specific index, ex- index 0 Thanks in Advance

1

1 Answers

0
votes

you can has a FormArray of FormControls or a FormArray of FormGroups (*)

//this insert a new FormControl in an Array of FormControls
this.detailsFormArray.insert(0,new FormControl())

//this insert a new FormControl in an Array of FormControls
this.detailsFormArray.insert(0,new FormGroup({
      prop1:new FormControl(),
      prop2:new FormControl(),
   }))
//or in steps
const group=new FormGroup({
   prop1:new FormControl(),
   prop2:new FormControl(),
})
this.detailsFormArray.insert(0,group)

Using FormBuilder

this.detailsFormArray.insert(0,this.fb.control())

//this insert a new FormControl in an Array of FormControls
this.detailsFormArray.insert(0,this.fb.group({
      prop1:[],
      prop2:[]
   }))

(*)

  • a FormArray.value of FormControls give you an array of string/number,etc, e.g. [0,1,2]
  • a FormArray.value of FormGroups give you an array of objects,e.g. [{id:1,name:'name1'},{id:2,name:'name2'}]