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