以 angular 反应形式在 FormArray 中设置数据

Set data in FormArray in angular reactive form

我有一个 FormGroup,其中包含一个表单数组,我想将我从 API 中获取的数据数组设置到该数组中,但显然我无法做到这一点。

表格

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());
}

这里我尝试设置值

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

Html代码

<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>

结果

错误

将 paragraphs() 创建为 getter 而不是函数,并像这样使用变量(不带 ()) -

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

然后使用 for 循环修补段落数组,其中数据是来自 API -

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

查看工作示例here