Angular 4 dynamic form patchvalue an array

Viewed 3920

I have a dynamic form based on the angular docs, I have a function that lets the user load their saved form. Currently i can patch the values of other form fields like textfield and radiobutton but I cant do it on an array since it's value is an array. I have the following code

if(value instanceof Array){
         value.forEach((subVal, index)=>{
           let a = subVal.value
           this.form.controls[key].patchValue({index,a})
         })
          //  
      }else{
      this.form.controls[key].patchValue(value);
      }
1 Answers

I would recommencd making a function and create the form there. When you saved the record or create it, should call the function.

If you want to update just one value can use .patchValue()

Like this:

createForm(data: any){
  let newFormArray: FormGroup[] = [];
  for(let i = 0; i > data.length; i++){
    newFormArray.push(this.fb.group({
                    id: data[i].id,
                    name: data[i].name
     }));
  }
  this.form = this.fb.group({
       array: this.fb.array(newFormArray)
  })
}
Related