简体   繁体   中英

Set data in FormArray in angular reactive form

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"
            class="form-control"></textarea>
    </td>
</tr>

Result

在此处输入图像描述

Error

在此处输入图像描述

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM