Home > Back-end >  Set data in FormArray in angular reactive form
Set data in FormArray in angular reactive form

Time:12-11

I have a FormGroup that contains a form 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

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"
            ></textarea>
    </td>
</tr>

Result

enter image description here

Error

enter image description here

CodePudding user response:

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

  • Related