Angular 2/4 编辑表单填充 FormArray 控件

Angular 2/4 Edit Form Populate FormArray Controls

我正在尝试为具有嵌套属性 (FormArray) 的模型实现编辑表单。我在语法上遇到了问题,我不确定我是否在正确的轨道上。主窗体的属性有效,这是我遇到问题的嵌套窗体。这是我目前所拥有的。

这里我发起表单群:

private initForm() {
  this.subscription = this.expenseService.getExpense(this.id)
    .subscribe(
      expense => {
        this.expense = expense;
        this.patchForm();
      }
    );
  this.expenseEditForm = this.fb.group({
    date: '',
    amount: '',
    check_number: '',
    debit: '',
    payee_id: '',
    notes: '',
    expense_expense_categories_attributes:[]
  });
}

我在这里修补表单以设置从我的后端检索到的对象的值 API。

private patchForm() {
  this.expenseEditForm.setValue({
    date: '',
    amount: this.expense.amount_cents,
    check_number: this.expense.check_number,
    debit: this.expense.debit,
    payee_id: '',
    notes: this.expense.notes,
    expense_expense_categories_attributes:  this.fb.array([
      this.setExpenseCategories(),
    ])
  });
}

这就是我卡住的地方。我如何推送到 FormArray。如果我尝试推送,我会收到一条错误消息,指出推送它在 FormArray 上不存在。

private setExpenseCategories() {
  for ( let expenseCategories of this.expense.expense_expense_categories){
    this.fb.array.push([
       this.fb.group({
        expense_category_id: [expenseCategories.expense_category_id, Validators.required],
        amount: [expenseCategories.amount_cents]
      ])
    });
  }
}

以防万一。这是我的 html.

<div
  *ngFor="let expensecategoriesCtl of expenseEditForm.controls.expense_expense_categories_attributes.controls let i = index"
  [formGroupName]="i"
  style="margin-top: 10px;">

  <md-card>
    <md-select class="full-width-input"
               placeholder="Expense Category"
               id="expense_category_id"
               formControlName="expense_category_id"
    >

      <md-option *ngFor="let expenseCategory of expenseCategories" value="{{expenseCategory.id}}">
        {{expenseCategory.category}}
      </md-option>
    </md-select>

    <md-input-container class="full-width-input">
      <input
        mdInput placeholder="Amount"
        type="number"
        formControlName="amount">
    </md-input-container>
  </md-card>
</div>

如果我正确理解你的问题,你可能需要这样的东西:

    // Update the data on the form
    this.productForm.patchValue({
        productName: this.product.productName,
        productCode: this.product.productCode,
        starRating: this.product.starRating,
        description: this.product.description
    });
    this.productForm.setControl('tags', this.fb.array(this.product.tags || []));

您可以在此处查看完整示例:https://github.com/DeborahK/Angular2-ReactiveForms 在 APM - 更新文件夹中。

对 DeborahK 的回答进行了一些更改,因为 expense.expense_expense_categories 不包含原始类型,而是包含对象。因此我们不能按原样分配值,但每个对象都需要包裹在 FormGroup 中,就像您尝试过的那样。

这里是你的代码的简化版本:

构建表单:

ngOnInit() {
  this.expenseEditForm = this.fb.group({
    notes: [''],
    // notice below change, we need to mark it as an formArray
    expense_expense_categories_attributes: this.fb.array([])
})

然后我们在回调中调用 patchForm,就像您所做的那样。该函数看起来像这样,注意,我们在外部调用 this.setExpenseCategories

patchForm() {
  this.expenseEditForm.patchValue({
    notes: this.expense.notes,
  })
  this.setExpenseCategories()
}

然后是现有代码的最大变化,我们首先将 FormArray 分配给变量 control 然后我们迭代从后端接收的数组,创建一个 FormGroup对于每个对象并将对象推送到每个 FormGroup:

setExpenseCategories(){
  let control = <FormArray>this.expenseEditForm.controls.expense_expense_categories_attributes;
  this.expense.expense_expense_categories.forEach(x => {
    control.push(this.fb.group(x));
  })
}

然后到模板,这个例子没有Angular Material:

<form [formGroup]="expenseEditForm">
  <label>Notes: </label>
  <input formControlName="notes" /><br>
  <!-- Declare formArrayName -->
  <div formArrayName="expense_expense_categories_attributes">
    <!-- iterate formArray -->
    <div *ngFor="let d of expenseEditForm.get('expense_expense_categories_attributes').controls; let i=index"> 
      <!-- Use the index for each formGroup inside the formArray -->
      <div [formGroupName]="i">
      <label>Amount: </label>
        <input formControlName="amount" />
      </div>
    </div>
  </div>
</form>

终于有一个

Demo