'Angular How to patch value in the form array

I am using Angular8 and reactive forms. My ngOnInit is:

ngOnInit(): void {
  this.makeForm = this.fb.group(
    year: ['', Validators.required],
    amount: ['', Validators.required],
    desc: ['', Validators.required],
    details: new FormArray([
      this.det(),
    ]
  );
}

det() {
  return new FormGroup({
    for: new FormControl(''),
    remarks: new FormControl('')
  });
}

I have the data from the backend to patch the array:

 {
  "amount": 9000,
  "year": 1996,
  "id": 1,
  "desc": "P1",
  "details": [
    {
      "id": 1,
      "remarks": "ok",
      "for": "1"
    },
    {
      "id": 24,
      "remarks": "OK",
      "for": "1"
    },
    {
      "id": 25,
      "remarks": "OK",
      "for": "1"
    }
  ]
 }

I commonly patch the values with this method:

getppredit() {
  let data:any = this.shareService.ParentShare.value;
  let id = data.id;
  this.dataService.getdataEdit(id)
    .subscribe((result: any) => {
      let no = result.no;
      let year = result.year;
      this.makeForm.patchValue({
        no: no,
        year: year
      });
  });
}

The above code is used for normal patch, but how to patch the value inside of an array dynamically using Angular8's reactive forms?



Solution 1:[1]

here's how i would do it using FormArray, which tracks the value and validity state of an array of FormControl, FormGroup or FormArray instances:

export class Component implements OnInit {

  // initialize the FormArray with an empty array!
  formArray: FormArray = new FormArray([]);
  makeForm: FormGroup;

  ngOnInit() {
    this.makeForm = this.fb.group({
      no: ['', Validators.required],
      year: ['', Validators.required],
    });
  }

  getParEdit() {
    ...
    this.dataService.getDataEdit(id).subscribe(result => {
      const { no, year, details } = result;
      this.makeForm.patchValue({ no, year });

      if (details.length) {
        details.forEach(detail => {
          this.formArray.push(
            this.fb.group({
              id: new FormControl({ value: detail.id }),
              requestFor: new FormControl({ value: detail.requestFor }),
              remark: new FormControl({ value: detail.remark }),
            });
          );
        });
      }
    });
  }
}

you can dynamically create the FormGroup for each detail iteration, as well as the FormControls in each.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ChumiestBucket