首页 > 解决方案 > Angular 8 和 FormArrays 如何初始化下拉列表以选择数组附带的初始值

问题描述

我有一个下拉列表,用户可以从中选择多个项目,并且项目将被附加到一个数组中selectedInvoicesArray

Object.keys(selectedInvoices).forEach((key, index)=>{
   this.selectedInvoicesArray.push(this.invoicesList.filter(res => {
        return res.invoice_id == selectedInvoices[key] 
   }));
})

在 html 端,我们有一个*ngFor循环selectedInvoicesArray数组并将每个索引的信息显示到一个 div 中。

我需要的是显示一个下拉列表,其中包含ActiveInactive作为选项,一旦每个项目的部分显示在组件上,就会选择原始值,然后用户可以更改状态。

唯一的方法是使用FormArray.

所以我做了以下事情:

我创建了一个包含表单数组的表单组:

 <form [formGroup]="updateStatusForm">
   <mat-form-field *ngFor="let select of selectedInvoicesArray; let i = index">
    <mat-select [formControlName]="i">
     <mat-option *ngFor="let status of invoiceStatuses" [value]="status.id">{{status.name}}</mat-option>
    </mat-select>
   </mat-form-field>
 </form>

然后,我创建了 formGroup 脚本:

updateStatusForm: FormGroup;

createUpdateStatusForm(){
    this.updateStatusForm = this.fb.group({
      'statusesControl': new FormControl('')
    })
  }

createUpdateStatusForm()每次将新数组推入时,我都会调用selectedInvoicesArray

Object.keys(selectedInvoices).forEach((key, index)=>{
      this.selectedInvoicesArray.push(this.invoicesList.filter(res => {
        return res.invoice_id == selectedInvoices[key]

      }));
      this.createUpdateStatusForm()
    })

正如您在图像中看到的,下拉列表是空的。我需要将其设置为来自数组的初始值。

在此处输入图像描述

*ngFor正在迭代的内容selectedInvoicesArray如下:

<div *ngFor="let invoice of selectedInvoicesArray;let i = index;">

作为一个例子:

<div>
     Description: {{invoice[0].description}}
</div>

当我将 2 个或更多数组推入selectedInvoicesArray时,在每个部分中我都会看到 2 个或更多下拉列表:

在此处输入图像描述

但我无法设置每个生成的表单数组的初始值来显示名为is_active.

编辑

我接下来尝试的是循环selectedInvoicesArray并设置每个生成的表单数组的值:

Object.keys(this.selectedInvoicesArray).forEach(key=>{
      console.log(this.selectedInvoicesArray[key].invoices[0])

this.createUpdateStatusForm(this.selectedInvoicesArray[key].invoices[0].is_active);
})

和:

createUpdateStatusForm(status_id){
    this.updateStatusForm = this.fb.group({
      'statusesControl': new FormControl(status_id)
    })
  }

但我有以下错误:

无法读取 FormGroupDirective.addControl 处未定义的属性“获取”

标签: arraysangularangular-reactive-formsformarrayformgroups

解决方案


推荐阅读