How to patch an array into formarray

447 views Asked by At
 this.formgroup = formbuilder.group({
      ordering_data: formgroup.array([this.createOrder()]),
    });

  createOrder(): FormGroup {
    return this.fb.group({
      order: [null, [Validators.required]],
      section_menu_id: [null, [Validators.required]],
    });
  }

Api Result

[
  {
    "order": 0,
    "section_menu_id": 3
  },
  {
    "order": 1,
    "section_menu_id": 1
  },
  {
    "order": 2,
    "section_menu_id": 6
  },
]

I try to show all those data from api result on my form input. Can someone tell me how to patch the api result into formgroup. Thanks in advance

3

There are 3 answers

4
Emilien On BEST ANSWER

In my projects, I do something like this :

const data = [
  {
    "order": 0,
    "section_menu_id": 3
  },
  {
    "order": 1,
    "section_menu_id": 1
  },
  {
    "order": 2,
    "section_menu_id": 6
  },
];

constructor(private fb: FormBuilder) {}

ngOnInit() {
  this.formgroup = this.fb.group({
    ordering_data: this.fb.array(this.data.map(item => this.createOrder(item))),
  });
}

createOrder(item?: any): FormGroup {
  return this.fb.group({
    order: [item ? item.order : null, Validators.required],
    section_menu_id: [item ? item.section_menu_id : null, Validators.required],
  });
}
1
Akora On

Have you tried the following?

this.formGroup.controls.ordering_data.patchValue(apiResult);

Cannot test it locally. Maybe you could provide a stackblitz?

0
cagcak On

consider below but I didn't test it;

interface Order {
  order: number;
  section_menu_id: number;
}

ngOnInit() {
  this.formgroup = formbuilder.group({
     ordering_data: formgroup.array([]),
  });
}

createOrder(o: Order): FormGroup {
  return this.fb.group({
     order: [o.order, [Validators.required]],
     section_menu_id: [o.section_menu_id, [Validators.required]],
  });
}

getOrders() {
   this.http.get(url).subscribe(ordersResponse: Order[]) => {
     const ordering_data = this.formgroup.get('ordering_data') as FormArray;
     ordersResponse.forEach((o: Order) => {
        ordering_data.push(this.createOrder(o.order, o.section_menu_id));
     }

     this.formgroup.updateValueAnDValidity();
   });
}