Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Set data in FormArray in angular reactive form

I have a FormGroup that contains a from array to which I want to set an array of data that I get from an api, but apparently I don’t make it entirely possible.

Form

this.blog = this.fb.group({
      title: ['', Validators.required],
      description: ['', Validators.required],
      date: [date, [Validators.required, this.dateValidator]],
      companyId: ['', Validators.required],
      isActive: [false],
      paragraphs: this.fb.array([])
    });

paragraphs(): FormArray {
    return this.blog.get("paragraphs") as FormArray
  }

  newParagraph(): FormGroup {
    return this.fb.group({
      section: ''
    })
  }

  addParagraph() {
    this.paragraphs().push(this.newParagraph());
  }

Here I try to set the values

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

this.blog.setControl('paragraphs', this.fb.array(this.blogUpdate.paragraphs || []));

Html code

<tr *ngFor="let paragraph of paragraphs().controls; let i = index" [formGroupName]="i">
    <td colspan="2">
        Parrafo:
        <textarea formControlName="section" (change)="saverange($event, paragraph.value.paragraphId, i)" [value]="paragraph.value.section" type="text" rows="7"
        class="form-control"></textarea>
     </td>
</tr>

Result

enter image description here

Error

enter image description here

>Solution :

Create paragraphs() as getter instead of a function, and use it like a variable (without ()) like this –

get paragraphs(): FormArray {
  return this.blog.get("paragraphs") as FormArray
}

Then patch the paragraphs array using a for loop, where data is an array from API –

data.forEach(element => {
      this.paragraphs.push(this.fb.group(element))
    })

See the working example here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading