Angular 2/4 Edit Form Populate FormArray Controls

前端 未结 2 1000
野的像风
野的像风 2021-02-04 06:40

I\'m trying to implement an edit form for a model with nested attributes (FormArray). I\'m having trouble with the syntax and I\'m uncertain whether I\'m on the right track. Th

2条回答
  •  执笔经年
    2021-02-04 07:31

    Some changes to DeborahK's answer, since expense.expense_expense_categories doesn't contain a primitive types, but objects. Therefore we cannot assign the values as is, but each object needs to be wrapped in a FormGroup, just like you have attempted.

    Here I have a shortened version of your code:

    Build the form:

    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([])
    })
    

    Then we call patchForm in the callback, just like you have. That function would look like this, notice, we call this.setExpenseCategories outside:

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

    Then comes the biggest change from your existing code, where we first assign the FormArray to the variable control and then we iterate your array received from backend, create a FormGroup for each object and push the object to each FormGroup:

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

    Then to the template, this example is without Angular Material:


    Finally a

    Demo

提交回复
热议问题